C++中线程的创建一般是通过std::thread类实现的,具体的实现方式有以下几种:
1 使用函数名创建
void pcreat(int a)
{
cout << "start !" << a << endl;
}
int main()
{
thread p(pcreat,4); //如果函数无参则省略第二个参数,多参数直接加在后面即可
p.join();
return 0;
}
2 使用类对象创建
class X
{
public:
X() { cout << "constructor!" << endl; }
X(const X & m) { cout << "copy constructor called !" << endl; }
void operator()(int a) // 重载括号运算符。如果无参则为void operator()(){...}
{
cout << "start!" <<a<< endl;
}
};
int main()
{
X a;
thread p(a,4); //以对象a创建线程,并传递参数4,无参的话直接省略第二个参数,更多的参数直接加在后面
p.join();
return 0;
}