关于C++11 thread 的超详细介绍和使用

本文详细介绍了C++11中std::thread的使用,包括构造函数、析构函数、赋值操作、joinable、join和detach等方法,通过实例解析了线程的创建、同步和资源管理,帮助理解C++11线程库的基本用法。

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

  在windows上面启线程时,用的是windows的API,前辈说可以去学一下C++11 提供的线程库,比较方便灵活。下面就介绍一下thread的用法。

std::thread::thread

thread() noexcept;

(1) (C++11 起)

thread( thread&& other ) noexcept;

(2) (C++11 起)

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

(3) (C++11 起)

thread(const thread&) = delete;

(4) (C++11 起)

 构造新的 thread 对象。

1) 构造不表示线程的新 thread 对象。

2) 移动构造函数。构造表示曾为 other 所表示的执行线程的 thread 对象。此调用后 other 不再表示执行线程。

3) 构造新的 std::thread 对象并将它与执行线程关联。新的执行线程开始执行

4) 复制构造函数被删除; thread 不可复制。没有两个 std::thread 对象可表示同一执行线程。

std::thread::~thread

~thread();

  (C++11 起)

在下列操作后 thread 对象无关联的线程(从而可安全销毁)

std::thread::operator=

thread& operator=( thread&& other ) noexcept;

(1) (C++11 起)

这个例子是借鉴cppreference.com这个网站上面的,我详细的分析一下这个例子。

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

void f1(int n){
	for (int i = 0; i < 2; ++i) {
		std::cout << "Thread 1 executing\n";
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}

void f2(int& n){
	for (int i = 0; i < 2; ++i) {
		std::cout << "Thread 2 executing\n";
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}

class foo{
public:
	void bar(){
		for (int i = 0; i < 2; ++i) {
			std::cout << "Thread 3 executing\n&#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值