请看下面例子(参考):
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::unique_lock, std::defer_lock class MyMutex : public std::mutex { int _id; public: MyMutex (int id) : _id(id) {} int id() {return _id;} }; MyMutex mtx (101); void print_ids (int id) { std::unique_lock<MyMutex> lck (mtx); std::cout << "thread #" << id << " locked mutex " << lck.mutex()->id() << 'n'; } int main () { std::thread threads[10]; // spawn 10 threads: for (int i=0; i<10; ++i) threads[i] = std::thread(print_ids,i+1); for (auto& th : threads) th.join(); return 0; }
好了,本文先介绍到这里,我们基本上介绍完了 C++11 多线程编程中两种最基本的锁类型,后面我会继续更新有关 C++11 并发编程的博客,希望感兴趣的同学继续关注 ;-)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持<计算机技术网(www.ctvol.com)!!>。
—-想了解C++11 并发指南之Lock 详解分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/483688.html