- 一个简单的Hello, Concurrent World程序:
#include<iostream>
#include<thread>
using namespace std;
void hello()
{
cout << "Hello Concurrent World\n";
}
int main()//初始线程
{
thread t(hello);//每个线程都必须具有一个初始化函数
t.join();
return 0;
}
t.join();
的作用:
新的线程启动之后,初始线程继续执行。如果它不等待新线程结束,它就将自顾自地继续运行到main()的结束,从而结束程序——有可能发生在新线程运行之前。
- 通过函数对象创建线程
#include<iostream>
#include<thread>
using namespace std;
class Counter {
public:
Counter(int id, int numIterations)
:mId(id), mNumIterations(numIterations)
{}
void operator()() const
{
for (int i = 0; i < mNumIterations; i++)
{
cout << "Counter " << mId << " has value ";
cout << i << endl;
}
}
private:
int mId;
int mNumIterations;
};
int main()
{
//列表初始化
thread t1{ Counter{1, 20}};
Counter c(2, 12);
thread t2(c);
thread t3(Counter(3, 10));
t1.join();
t2.join();
t3.join();
return 0;
}
易错点
#include<iostream>
#include<thread>
using namespace std;
class Counter {
public:
Counter(){}
void operator()() const
{}
};
int main()
{
/*
如果你传递了一个临时变量,而不是一个命名的变量;
C++编译器会将其解析为函数声明,而不是类型对象的定义。
其参数是一个指针,指向返回一个Counter对象的无参函数
*/
// thread t2(Counter());
thread t2((Counter()));
t2.join();
return 0;
}
- 通过
lambda
创建线程
#include<iostream>
#include<thread>
using namespace std;
int main()
{
int id = 1;
int numberIterations = 100;
thread t4([id, numberIterations] {
for (int i = 0; i < numberIterations; ++i) {
cout << "Counter " << id << " has value ";
cout << i << endl;
}
});
t4.join();
return 0;
}
lambda
表达式:
lambda
表达式是C++11的一个新特性,它允许使用一个可以捕获局部变量的局部函数