C++11线程指南(2)--Lambda线程实现

目录

1.线程使用lambda函数

2.并发程序的特性


1.线程使用lambda函数

  基于前一章中的Lambda程序,我们进行了扩展,当前创建5个线程。

#include<iostream>
#include<thread>
#include<vector>
#include<algorithm>

int main()
{
	std::vector<std::thread> threadVec;
	for(int i=0; i<5; ++i){
		threadVec.push_back(std::thread([]() 
		{
			std::cout<<"thread function\n";
		}));
	}
	std::cout<<"main thread\n";

	std::for_each(threadVec.begin(), threadVec.end(), [](std::thread & thr) 
	{
		thr.join();
	});
	return 0;
}

  运行结果为:
  thread function
  thread function
  thread function
  main thread
  thread function
  thread function

2.并发程序的特性

  上述运行结果中,无法确定是哪个线程打印出了哪个结果。所以下面程序中插入一个标记。

	for(int i=0; i<5; ++i){
		threadVec.push_back(std::thread([i]() 
		{
			std::cout<<"thread function "<<i <<"\n";
		}));
	}
	std::cout<<"main thread\n";

  得到的结果是:
  thread function 0
  thread function 3
  main thread
  thread function 2
  thread function 1
  thread function 4

  或者
  thread function 0
  thread function 1
  thread function main thread
  3
  thread function 4
  thread function 2

  从中可以看到,多线程并发有着天然的不确定性。每次运行都可以得到不同的结果。调度器可以在任意的时间被中断。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值