CPP创建子线程

发布时间 2023-12-24 14:38:25作者: 81

 

#include <iostream>
#include<thread>

using namespace std;

struct MyStruct
{
      int a = 0;
      string s = "abc雷";
};

//线程入口 void proc(MyStruct& a) { for (int m = 0; m < 50; m++) { if (a.a == 0) { cout << "线程中断" << endl; break; } std::chrono::milliseconds sd(1000); this_thread::sleep_for(sd); cout << "我是子线程,传入参数为" << a.a << a.s<< endl; cout << "子线程中显示子线程id为" << this_thread::get_id() << endl; }
//函数执行完,线程停止 } int main() { MyStruct my; my.a = 20; my.s = "aa雷"; //thread th2(proc, &my); thread th2(proc, ref(my));//第一个参数为函数名,第二个参数为该函数的第一个参数,如果该函数接收多个参数就依次写在后面。此时线程开始执行。 cout << "主线程中显示子线程id为" << th2.get_id() << endl; //此处省略多行,不要在创建完线程后马上join,应该在程序结束前join this_thread::sleep_for(std::chrono::milliseconds(2000)); //主线程休眠2s my.a = 0; //触发子线程停止 th2.join();//此时主线程被阻塞直至子线程执行结束。 std::cout << "Hello World!\n"; }