c++11新特性之多线程总结
一、线程初始化方式
std::thread thread_1(thread1);
if (thread_1.joinable()) thread_1.join();
std::thread thread_2(thread2, 2);
if (thread_2.joinable()) thread_2.join();
std::thread(thread2, 3).detach();
auto lambda = [](int a) {
std::cout << "lambda : " << a << std::endl;
};
std::thread thread_3(thread3, 3);
std::this_thread::sleep_for(std::chrono::seconds(5));
std::thread thread_4(thread4, 4);
std::thread thread_5(lambda, 5);
std::cout << "当前 cpu 个数 " << std::thread::hardware_concurrency() << std::endl;
if (thread_3.joinable())
thread_3.join();
if (thread_4.joinable())
thread_4.join();
if (thread_5.joinable())
thread_5.join();
二、总结
1.detach()是将子线程与主线程分离,成为孤儿线程
2.孤儿线程通信方式:
#include <queue>
std::mutex cv_mutex;
void produceA(std::queue<char>& q) {
std::unique_lock<std::mutex> lock;
for(auto i