本文主要是介绍C++11: 多线程thread, 锁lock、lock_guard, 条件变量conditional详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 线程定义
- 线程实现
- ref:修改线程函数变量作用域
- join
- detach
- mutex锁
- lock
- try_lock
- lock_guard
- lock_unique
- 条件变量(condition)
线程定义
实现并行,避免主线程的阻塞
线程实现
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; // 10cout<<"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
这篇关于C++11: 多线程thread, 锁lock、lock_guard, 条件变量conditional详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!