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