C++ Thread

围绕3点去讨论线程问题:线程创建,线程回收,以及线程状态

1 std::thread有如下的构造方式:
1). 默认构造函数: thread() noexcept;
2). 移动语义的构造方式:thread( thread&& other ) noexcept;
3).传入一个Function,function可以是lambda,全局函数,std::function的对象,函数对象,C++20之后也可以是std::invoke
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
4). thread( const thread& ) = delete; 也就意味着不能调用拷贝构造

代码示例:

先定义如下类和函数,用来创建线程:

测试函数如下:

输出结果:
threadCreateTest 59 2: joinable 1
threadCreateTest 62 2: joinable 0
threadTestFunction 48 2
threadTestFunction 48 2
threadCreateTest 66 joined
func ptr 0x68fd17
thread lambda
operator() 32 4
this ptr 0x1d1638
threadFunc 39 5
this ptr 0x68fd17 tmp 11

 2 线程回收:
   1) detach
   2) join
   detach之后的线程不能join会报错.
   没有deatch的线程不调用join会报terminate
   线程join之前始终需要判断joinbale避免terminate报错

以上测试代码输出结果:

    testRecycle 121 joinbale 0
    testRecycle 126 joinbale 1

3 线程交换:swap

  输出结果:
    trSrc     tid 2
    trTraget  tid 3
    trSrc     tid 3
    trTraget  tid 2
    可以发现两个线程的tid被交换

  4 operator=: thread& operator=( thread&& other ) noexcept;
    如果当前线程是joinable将会发生std::terminate()

无论出于何种设计使用C++的thread始终需要注意它的线程可回收状态。否则容易出现terminate报错

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用:在C++11中,通过引入<thread>头文件,可以使用std::thread类来创建和管理线程。std::thread类封装了线程的创建、调度和销毁等操作,使得多线程编程更加方便。 在引用的代码片段中,main函数创建了一个包含5个线程的线程数组。然后使用for循环,对每个线程调用std::thread类的构造函数来创建线程。线程的执行函数是thread_task,并传递一个参数i+1。接下来,通过调用join()函数,等待每个线程执行完毕。最后,输出"All threads joined"表示所有线程都已经执行完毕。 在引用的代码片段中,independentThread函数是一个独立的线程函数,它会在启动后等待2秒钟,然后输出"Exiting concurrent thread"。threadCaller函数是另一个线程函数,它会创建一个新的线程t,并将独立线程函数independentThread绑定到t上。然后,通过调用t.detach()将线程t分离,使得线程t的执行与主线程并行。在threadCaller函数中,同时还有一个睡眠1秒的操作,并输出"Exiting thread caller"。最后,主函数main调用threadCaller函数,并在之后睡眠5秒钟。 综上所述,C++11中的<thread>头文件和std::thread类提供了方便的多线程编程接口,可以通过创建和管理线程对象来实现并行执行的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C++11(std::thread)](https://blog.csdn.net/wuchalilun/article/details/48160393)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [C++ thread用法总结(整理)](https://blog.csdn.net/sevenjoin/article/details/82187127)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值