C++中线程的创建一般是通过std::thread类实现的,具体的实现方式有以下几种:
1 使用函数名创建
void pcreat(int a)
{
cout << "start !" << a << endl;
}
int main()
{
thread p(pcreat,4); //如果函数无参则省略第二个参数,多参数直接加在后面即可
p.join();
return 0;
}
![](https://img-blog.csdnimg.cn/20190306220041797.png)
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;
}
![](https://img-blog.csdnimg.cn/20190306215444352.png)
实现这种方式的重点是重载了括号运算符。还需要注意的是,这里调用了一次拷贝构造函数,这是因为用对象来创建线程时,会自动拷贝该对象到子线程中。
3 使用lambda创建
int main()
{
auto f = [](int a, int b){
cout << "lambda pthread creat" << endl;
cout << a << " " << b << endl; };
thread p(f,3,4);
p.join();
return 0;
}
![](https://img-blog.csdnimg.cn/20190307154216227.png)
4 使用成员函数创建
这里有两种方法通过成员函数创建。而这两种方法恰好也就是静态成员函数和非静态成员函数的区别。静态成员函数与对象无关,只属于类本身,因此在创建线程时只需要给出静态成员函数地址即可;而非静态成员函数是属于对象的,只有在对象创建后才能够调用,因此在创建线程时必须还要传递对象的地址。
通过静态成员函数创建线程:
class A
{
public:
static void fun(int a)
{
cout << a << endl;
return;
}
};
int main()
{
int x = 5;
thread p(&A::fun,x);
p.join();
return 0;
}
非静态成员函数创建线程:
class A
{
public:
void fun(int a)
{
cout << a << endl;
return;
}
};
int main()
{
int x = 5;
A a;
thread p(&A::fun,&a,x); //必须传入对象的地址,即this指针,才能找到线程函数的地址
p.join();
return 0;
}