C++ Thread使用类成员函数

发布时间 2023-11-24 17:21:51作者: 量子与太极

C++ Thread使用类成员函数

 1 #include <thread>
 2 #include <iostream>
 3 
 4 using std::cout;
 5 using std::endl;
 6 using std::thread;
 7 
 8 class Job {
 9 public:
10   Job(int m) : _m(m){}
11   void doSomeThing(int a, int b) {
12     int c = a + b + _m;
13     cout << "c : " << c << endl;
14   }
15 private:
16   int _m;
17 };
18 
19 int main() {
20   Job j(3);
21   thread t(&Job::doSomeThing, &j, 1, 3);
22 
23   t.join();
24   return 0;
25 }

 

创建线程thread t(&Job::doSomeThing, &j, 1, 3)时需要传入实例化对象Job j的引用。