围绕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报错