C++11 thread用法

线程(std::thread)

std::thread的简介时候,能够知道
std::thread
Member types

  • id //thread id
  • native_handle_type //Native handle type

Member functions

  • (constructor) //construct thread
  • (destructor) //Thread destructor
  • operator= //Move-assign thread
  • get_id //Get thread id
  • joinable //Check if joinable(可结合的)稍后解释可结合的意思
  • join //join thread
  • detach //Detach thread
  • swap //swap threads
  • native_handle //Get native handle
  • hardware concurrency[static] // detect hardware concurrency

non-member overloads

  • swap(thread) // Swap threads(function)

因为类数据成员我们看注释都可以读懂相关的含义,所以直接上相关的成员函数

先是初始化
我们在初始化直接使用

std::thread name (function)这样的格式即可,如果我们不用后面的小括号的话,只进行线程的命名,那么就是进行了默认初始化

thread线程常用函数:

joinable():

joinabe成员函数的作用在c++官方文档中是返回线程是否是可结合的。
可结合的意思就是,一个线程是否能够被执行Join或者是detch操作,因为相同的线程不能被join两次,也不能join完再进行detach,同理也不可以被detach两次,所以joinable函数就是判断是否能进行可结合。
在c++的官方文档中列出了不能被joinable的情况。

在c++的官方文档中列出了不能被joinable的情况。

  • 是被默认构造的(即没有小括号的构造语句)std::thread name;
  • 执行过move操作
  • 执行过join或者detach

join():

join在从c++官方文档的介绍中,我们可以知道,join是用来进行同步的一个工具,当我们在主进程中使用join了一个子进程,那么我们主进程就要等待这个子进程运行完毕,并且回收子进程的资源后,再执行主进程的程序。

detach():

我们先从detach的字面意思进行理解下,detach指的是分离,脱离的意思,那么我们引申过来,在线程中的话,detach的意思就是将主线程和子线程进行分离,主线程是不会再等待子线程。
那么这个时候会有一个疑问,就是主线程结束的时候,进程也就结束,那么是不是表示子线程也是结束。结果不是,子线程的输出只是不进行显示,它还是会运行完,再被回收。

如果删除掉了join试图运行时,发现它是按照不同顺序来进行的,但是运行到最后会出现abort() has been called,搜查了相关资料发现,join以后会表示这个线程可以destroy了,那么在子线程结束后会进行相关资源的回收,但是如何没有join或者detach,就会导致不会产生标记,在最后整个进程结束时,该回收的资源没有回收,就会产生错误。

实际使用的example:

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

thread thRev;
thread thSend;

/// 互斥锁 用于线程之间同步数据
std::mutex mtx;

///  接收线程或读线程
void funRev() {
    while(true) {
        if (mtx.try_lock()) {

            /// 操作部分
            mtx.unlock();
        }
    }  
}

 /// 发送线程或写线程
void funSend() {
    while(true) {
    
        if (mtx.try_lock()) {
              
              /// 操作部分
              mtx.unlock();
        }
    }
}

int main() {

    // 创建线程
    thRev = thread(funRev);
    thSend = thread(funSend);

    thRev.join();
    thSend.join();

    return 0;
}        

参考:

https://www.cnblogs.com/Yekko/p/13508941.html

原文地址:https://www.cnblogs.com/xiaohaigegede/p/13596268.html