原始C++标准仅支持单线程编程。新的C++标准(称为C++11或C++0x)于2011年发布。在C++11中,引入了新的线程库。因此运行本文程序需要C++至少符合C++11标准。

2 连接和分离线程

在本章中,我们将讨论std::thread的连接和分离。

2.1 用std::thread::join()连接线程

一旦启动一个线程,则另一个线程可以等待该新线程完成。为此,还需要在std::thread对象上调用join()函数,即

std::thread th(funcPtr);
// Some Code
th.join();

让我们看一个例子,假设主线程必须启动10个工作线程,并且在启动所有这些线程之后,主函数将等待它们完成。连接所有线程后,主函数将继续。

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector> class WorkerThread
{
public:
void operator()()
{
std::cout << "Worker Thread " << std::this_thread::get_id() << " is Executing" << std::endl;
}
};
int main()
{
// 创建多个线程
std::vector<std::thread> threadList;
for (int i = 0; i < 10; i++)
{
threadList.push_back(std::thread(WorkerThread()));
}
// Now wait for all the worker thread to finish i.e.
// Call join() function on each of the std::thread object
// 现在等待所有工作线程完成,即对每个std::thread对象调用join()函数
std::cout << "wait for all the worker thread to finish" << std::endl;
std::for_each(threadList.begin(), threadList.end(), std::mem_fn(&std::thread::join));
std::cout << "Exiting from Main Thread" << std::endl;
return 0;
}

输出为:

Worker Thread 12616 is ExecutingWorker Thread 10584 is Executing

Worker Thread Worker Thread 14696Worker Thread Worker Thread 15356Worker Thread 11228 is Executing
Worker Thread is Executing is Executing
9528 is Executing
Worker Thread
wait for all the worker thread to finish
Worker Thread 16312 is Executing
14448 is Executing77361908 is Executing is Executing
Exiting from Main Thread

2.2 使用std::thread::detach()分离线程

分离的线程也称为守护进程/后台线程。要分离线程,我们需要对std::thread对象调用std::detach()函数,即:

std::thread th(funcPtr);
th.detach();

调用detach()之后,std::thread对象不再与实际的执行线程关联。
注意在线程句柄上调用detach()和join()时要小心!!

情况1:永远不要在没有关联执行线程的std::thread对象上调用join()或detach()

    std::thread threadObj( (WorkerThread()) );
threadObj.join();
// 这将导致程序终止 It will cause Program to Terminate
threadObj.join();

当在线程对象上调用join()函数时,则当此join返回0时,则std::thread对象没有与其关联的线程。如果再次在该对象上调用join()函数,则将导致终止程序。同样,调用detach()可以使std::thread对象不与任何线程函数链接。在那种情况下,在std::thread对象上调用detach函数两次将导致程序终止。

    std::thread threadObj( (WorkerThread()) );
threadObj.detach();
// 这将导致程序终止 It will cause Program to Terminate
threadObj.detach();

因此,在调用join()或detach()之前,我们应该检查每次线程是否可连接,即

    std::thread threadObj( (WorkerThread()) );
if(threadObj.joinable())
{
std::cout<<"Detaching Thread "<<std::endl;
threadObj.detach();
}
if(threadObj.joinable())
{
std::cout<<"Detaching Thread "<<std::endl;
threadObj.detach();
} std::thread threadObj2( (WorkerThread()) );
if(threadObj2.joinable())
{
std::cout<<"Joining Thread "<<std::endl;
threadObj2.join();
}
if(threadObj2.joinable())
{
std::cout<<"Joining Thread "<<std::endl;
threadObj2.join();
}

情况2:不要忘记在具有关联的执行线程的std::Thread对象上调用Join或Detach
如果具有关联的执行线程的std::Thread对象没有调用Join或Detach,则在该对象的析构期间-否则它将终止程序。因为在析构内部-或者它检查线程是否仍然是可联接的,然后终止程序,即

#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
void operator()()
{
std::cout << "Worker Thread " << std::endl;
}
};
int main()
{
std::thread threadObj((WorkerThread()));
// Program will terminate as we have't called either join or detach with the std::thread object.
// Hence std::thread's object destructor will terminate the program
// 程序将终止,因为我们没有使用std::Thread对象调用Join或Detach。因此std::Thread的对象析构函数将终止程序
return 0;
}

输出为:

Worker Thread
程序崩溃

同样,在发生异常的情况下,我们不应忘记调用join()或detach()。为了防止这种情况,我们应该使用“资源获取初始化”( RESOURCE ACQUISITION IS INITIALIZATION,RAII),即

#include <thread>
#include <iostream> class ThreadRAII
{
std::thread & m_thread;
public:
ThreadRAII(std::thread & threadObj) : m_thread(threadObj)
{
}
~ThreadRAII()
{
// Check if thread is joinable then detach the thread
// 检查线程是否连接,然后分离线程
if (m_thread.joinable())
{
m_thread.detach();
}
}
};
void thread_function()
{
for (int i = 0; i < 10000; i++);
std::cout << "thread_function Executing" << std::endl;
} int main()
{
std::thread threadObj(thread_function); // If we comment this Line, then program will crash
// 如果我们注释此行,则程序将崩溃
ThreadRAII wrapperObj(threadObj);
return 0;
}

输出为:

thread_function Executing

2.3 参考

https://thispointer.com//c11-multithreading-part-3-carefully-pass-arguments-to-threads/

[编程基础] C++多线程入门2-连接和分离线程的更多相关文章

  1. [编程基础] C++多线程入门6-事件处理的需求

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 6 事件处 ...

  2. [编程基础] C++多线程入门7-条件变量介绍

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 7 条件变 ...

  3. [编程基础] C++多线程入门4-数据共享和资源竞争

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++ 11标准. 4 数据共享和资源 ...

  4. [编程基础] C++多线程入门5-使用互斥锁解决资源竞争

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 5 使用互 ...

  5. [编程基础] C++多线程入门8-从线程返回值

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 8 从线程返回值 8 ...

  6. [编程基础] C++多线程入门1-创建线程的三种不同方式

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 1 创建线程的三种不 ...

  7. [编程基础] C++多线程入门10-packaged_task示例

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 10 pa ...

  8. [编程基础] C++多线程入门9-async教程和示例

    原始C++标准仅支持单线程编程.新的C++标准(称为C++11或C++0x)于2011年发布.在C++11中,引入了新的线程库.因此运行本文程序需要C++至少符合C++11标准. 文章目录 9 asy ...

  9. [编程基础] C++多线程入门3-小心地将参数传递给线程

    原始C++标准仅支持单线程编程.新的C++标准(称为c++11或c++0x)于2011年发布.在c++11中,引入了新的线程库.因此运行本文程序需要C++至少符合c++11标准. 文章目录 3 小心地 ...

随机推荐

  1. 【软件学习】如何下载安装Mathtype,并将其加载至Word

    参考视频: https://www.bilibili.com/video/BV1cV41117SR?from=search&seid=11224207889712369816 首先,需要安装. ...

  2. Python生成10个八位随机密码

    #生成10个八位随机密码 import random lst1=[ chr(i) for i in range(97,123) ] #生成26为字母列表 lst2=[i for i in range( ...

  3. Java中的名称命名规范

    包名:多单词组成时所有字母都小写:xxxyyyzzz 类名.接口名:多单词组成时,所有单词的首字母大写:XxxYyyZzz 变量名.方法名:多单词组成时,第一个单词首字母小写,第二个单词开始每个单词首 ...

  4. cudaMemcpy cudaMalloc

    cudaMemcpy有四种类型:HostToHost, DeviceToHost, HostToDevice, DeviceToDevices 现在我有两个指针:h_ptr, d_ptr,分别指向ho ...

  5. Vue学习之--------Vue中收集表单数据(使用v-model 实现双向数据绑定、代码实现)(2022/7/18)

    文章目录 1.Vue中实现表单数据的收集 1.1 基础知识 1.2 代码实例 1.3 测试效果 1.4 额外插一嘴 1.Vue中实现表单数据的收集 1.1 基础知识 表单中常用的标签:input(输入 ...

  6. NLP之基于Seq2Seq和注意力机制的句子翻译

    Seq2Seq(Attention) @ 目录 Seq2Seq(Attention) 1.理论 1.1 机器翻译 1.1.1 模型输出结果处理 1.1.2 BLEU得分 1.2 注意力模型 1.2.1 ...

  7. NLP之基于TextCNN的文本情感分类

    TextCNN @ 目录 TextCNN 1.理论 1.1 基础概念 最大汇聚(池化)层: 1.2 textCNN模型结构 2.实验 2.1 实验步骤 2.2 算法模型 1.理论 1.1 基础概念 在 ...

  8. 从源码入手探究一个因useImperativeHandle引起的Bug

    今天本来正在工位上写着一段很普通的业务代码,将其简化后大致如下: function App(props: any) { // 父组件 const subRef = useRef<any>( ...

  9. <四>1:全面掌握Const的用法

    const怎么理解? const修饰的变量不能够在作为左值!!初始化完成后,值不能被修改!! C 和C++中const 的区别? 在C程序中 test.c const int a; 只定义,不做初始化 ...

  10. 【多服务场景化解决方案】AR虚拟技术助力智能家装

    ​ 1 .介绍 总览 本应用采用了华为图形引擎服务的AR虚拟技术,您可以在手机相机里摆放想要购置的家具家电,交互式体验让您可以轻松操控它们的3D图例,以此来确定这些家具家电是否适合摆放在您的家里. 特 ...