c++11&14-多线程要点汇总

2020-06-03 11:00:35于丽

3. std::condition_variable

C++11中的std::condition_variable就像Linux下使用pthread_cond_wait和pthread_cond_signal一样,可以让线程休眠,直到被唤醒,然后再重新执行。线程等待在多线程编程中使用非常频繁,经常需要等待一些异步执行的条件的返回结果。

代码如下:

#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
 std::unique_lock<std::mutex> lck(mtx);
 while (!ready) cv.wait(lck); //线程将进入休眠
 // ...
 std::cout << "thread " << id << 'n';
}
void go() {
 std::unique_lock<std::mutex> lck(mtx);
 ready = true;
 cv.notify_all();
}
int main()
{
 std::thread threads[10];
 // spawn 10 threads:
 for (int i = 0; i<10; ++i)
  threads[i] = std::thread(print_id, i);
 std::cout << "10 threads ready to race...n";
 go(); // go!
 for (auto& th : threads) th.join();
 return 0;
}

运行结果:

10 threads ready to race...
thread 0
thread 1
thread 2
thread 3
thread 4
thread 5
thread 6
thread 7
thread 8
thread 9

上面的代码,在调用go函数之前,10个线程都处于休眠状态,当cv.notify_all()运行后,线程休眠结束,继续往下运行,最终输出如上结果。

以上就是c++11&14-多线程知识汇总的详细内容,更多关于c++11&14 多线程使用的资料请关注易采站长站其它相关文章!