c++11 标准库中的线程库

本文详细介绍了线程库的使用方法,并通过实例展示了如何利用线程进行多线程编程,包括函数类实现、线程创建、参数传递(传值与传引用)的区别以及线程间数据的隔离。

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

原文url:http://www.devx.com/SpecialReports/Article/38883

线程库的用法:

void do_work();  //定义线程执行函数

std::thread t(do_work); //创建新线程

这样的执行就相当于我们定义一个“函数类”(一个实现了‘()’操作符的类)

class do_work  

{  public:  

void operator()();  

int    status;

};  

do_work dw;  

std::thread t(dw);//这里实际调用的是do_work类的拷贝构造函数,新建线程中status变量的修改不会影响到主线程中dw.status的值。

参考下面的代码,了解传值和传引用的区别。

#include <thread>
#include <chrono> //秒表
#include <iostream>
using namespace std;

class do_work    
{    
	
public:

	do_work():status(0)//ctor
	{

	};

	void operator()() //重载() 操作符
	{
		for (int i = 0; i < 100; i ++){
			this_thread::sleep_for(chrono::milliseconds(10));
			status ++;
		}
		cout << "sub thread finish" << endl;
	};    
	
	int    status;
};

void main(){
	do_work dw; 

	dw.status = 0;
	cout << "before sub thread complete " << dw.status << endl;
	std::thread subThread(dw); // 传值
	subThread.join();
	cout << "after sub thread complete " << dw.status << endl;

	dw.status = 0;
	cout << "before sub thread complete " << dw.status << endl;
	std::thread subThread2(std::ref(dw)); // 传引用   std::thread subThread2(&dw) //compile fail
	subThread2.join();
	cout << "after sub thread complete " << dw.status << endl;
}

/*
运行结果
before sub thread complete 0
sub thread finish
after sub thread complete 0
before sub thread complete 0
sub thread finish
after sub thread complete 100
请按任意键继续. . .
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值