makesurethreadgroup.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <thread>
  2. #include <mutex>
  3. #include <condition_variable>
  4. #include <iostream>
  5. #include <vector>
  6. #include <memory>
  7. std::mutex mymutex;
  8. std::condition_variable mycv;
  9. bool success = false;
  10. void thread_func()
  11. {
  12. {
  13. std::unique_lock<std::mutex> lock(mymutex);
  14. success = true;
  15. mycv.notify_all();
  16. }
  17. //实际的线程执行的工作代码放在下面
  18. //这里为了模拟方便,简单地写个死循环
  19. while (true)
  20. {
  21. }
  22. }
  23. int main()
  24. {
  25. std::vector<std::shared_ptr<std::thread>> threads;
  26. for (int i = 0; i < 5; ++i)
  27. {
  28. std::shared_ptr<std::thread> spthread;
  29. spthread.reset(new std::thread(thread_func));
  30. //使用花括号减小锁的粒度
  31. {
  32. std::unique_lock<std::mutex> lock(mymutex);
  33. while (!success)
  34. {
  35. mycv.wait(lock);
  36. }
  37. }
  38. std::cout << "start thread successfully, index: " << i << std::endl;
  39. threads.push_back(spthread);
  40. }
  41. for (auto& iter : threads)
  42. {
  43. iter->join();
  44. }
  45. return 0;
  46. }