用std::bind创建线程函数
时间: 2023-11-16 12:52:54 浏览: 34
使用std::bind函数可以创建线程函数。std::bind函数可以将成员函数与对象实例进行绑定,生成一个可调用对象,然后将该可调用对象作为线程函数的参数传入std::thread构造函数中。
以下是使用std::bind创建线程函数的示例代码:
```
#include <iostream>
#include <thread>
#include <functional>
class MyClass {
public:
void threadFunc(int x) {
std::cout << "Thread function started" << std::endl;
std::cout << "x = " << x << std::endl;
// 在线程函数中修改x的值
x++;
std::cout << "x = " << x << std::endl;
std::cout << "Thread function ended" << std::endl;
}
};
int main() {
MyClass obj;
int x = 10;
// 使用std::bind将成员函数与对象实例进行绑定
auto func = std::bind(&MyClass::threadFunc, &obj, x);
// 创建线程并传入绑定后的函数对象
std::thread t(func);
t.join();
return 0;
}
```
在上面的例子中,我们使用std::bind将类的成员函数MyClass::threadFunc与对象实例obj进行绑定,并将变量x作为参数传入。然后创建线程t,并将绑定后的函数对象func作为线程函数的参数传入。