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

原文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
请按任意键继续. . .
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值