C++多线程编程之thread类详解

本文详细介绍了C++中的thread类,包括构造函数、析构函数、成员函数如get_id、detach、join等,以及数据成员和静态成员函数。还讨论了线程的joinable状态和non-joinable状态的重要性。此外,文章提到了std::this_thread命名空间的相关函数,如get_id、yield、sleep_for和sleep_until。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

thread

构造函数

1、默认构造函数

2、带形参的构造函数

3、拷贝构造函数

4、移动构造函数

析构函数 

成员函数

thread::get_id

thread::detach

thread::join

thread::joinable

joinable状态和非joinable状态

 thread::operator=

thread::swap

thread::native_handle(难搞)

数据成员

thread::id

thread::native_handle_type(难搞)

静态成员函数

thread::hard_ware_concurrency

友元函数

std::swap

this_thread

std::this_thread::get_id

std::this_thread::yield

std::this_thread::sleep_for

std::this_thread::sleep_until


thread

头文件:thread
名称空间:std
thread类用于创建线程对象

构造函数

1、默认构造函数

thread() noexcept;//默认构造函数

默认构造函数会构造一个thread对象,但该对象不表示任何可执行的线程,并且不是joinable
noexcept形如其名地,表示其修饰的函数不会抛出异常。这是因为异常机制会带来一些额外开销,比如函数抛出异常,会导致函数栈被依次地展开,并依帧调用在本帧中已构造的自动变量的析构函数等。

#include <iostream>
#include <thread>
int main(int argc, char*argv[]){
	//使用默认构造函数创建对象,non-joinable状态
	std::thread th1;
}

2、带形参的构造函数

//带形参的构造函数
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);

该构造函数会构造一个thread对象,表示新的可执行的joinable线程。新线程会调用fn,而args用于初始化fn的形参。
fn可以是函数指针对象成员函数指针,或任何的移动构造函数对象(如定义了opearotr()的类对象),返回值被忽略。
该构造的完成与该fn副本的调用开始同步。

void f1(string str){
	cout << str << endl;
}
class A{
public:
	void operator()(string str){
		cout << str << endl;
	}
};
int main(){
	thread th1(f1, "我是第一个子线程");//传递函数
	auto f2 = [](string str){cout << str << endl;};
	thread th2(f2, "我是第二个子线程");//传递lambda表达式
	A a;
	thread th3(a, "我是第三个子线程");//传递重载了调用运算符()的类对象
	th1.join();
	th2.join();
	th3.join();
	return 0;
}

3、拷贝构造函数

thread (const thread&) = delete;

拷贝构造函数被delete,不可用。

4、移动构造函数

thread (thread&& x) noexcept;

将线程x移交给新线程,需要使用std::move()函数。此后,x不在拥有该线程,且处于non-joinable状态,但可以再用赋值运算符将另一个线程移交给x。

int main()
{
	auto f = [](string str) {cout << str << endl; };
	/*----------------------------------------------*/
	thread th1(f, "我是子线程");
	if (th1.joinable() == true)
		cout << "th1 is joinable" << endl;
	else 
		cout << "th1 is non-joinable" << endl;
	/*----------------------------------------------*/
	thread th2(move(th1));//移交给新线程th2
	if (th1.joinable() == true)
		cout << "th1 is joinable" << endl;
	else
		cout << "th1 is non-joinable" << endl;
	/*----------------------------------------------*/
	thread th3(f, "我也是子线程");
	th1 = move(th3);
	if (th1.joinable() == true)
		cout << "th1 is joinable" << endl;
	else
		cout << "th1 is non-joinable" << endl;
	/*----------------------------------------------*/
	th1.join();
	th2.join();
	//此时th3不需要等待,因为此时th3为non-joinable
	return 0;
}

析构函数 

~thread();

析构函数销毁thread对象。当线程是joinable时,销毁线程时将调用terminate()<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值