八月的雨季 最後的冰吻

八月的雨季 最後的冰吻

线程定义

实现并行,避免主线程的阻塞

线程实现
void func()
{
   
    cout<<"thread func :"<<this_thread::get_id()<<endl;
}

int main()
{
   
    cout<<"main thread :"<<this_thread::get_id()<<endl;
    thread t(func);
    t.join();
    cout<<"thread is over"<<endl;
    return 0;
}
输出:
main thread :1
thread func :2
ref:修改线程函数变量作用域
void func(int &n)
{
   
    cout<<n<<endl;
    n = 10;
}

int main()
{
   
    int n = 5;
    thread t(func,ref(n));
    t.join();
    cout<<n<<endl; // 10
    cout<<"thread is over"<<endl;
    return 0;
}
输出:
5
10
thread is over
join

join:阻塞主线程,子线程调用jion后,主线程需要等待子线程执行完后,再继续执行
join阻塞主进程结束,对子线程的执行没有影响

code:

void func()
{
   
    cout<<"thread func :"<<this_thread::get_id()<<endl;
    this_thread::sleep_for(chrono::seconds(10));
}

void func2
03-25 07:11