Guest User

Untitled

a guest
Aug 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. //*.cxx
  2. #include <iostream>
  3. #include <mutex>
  4. #include <shared_mutex> // requires c++14
  5. #include <thread>
  6. #include <vector>
  7.  
  8. namespace {
  9. std::mutex g_msgLock;
  10. std::shared_timed_mutex g_testingLock;
  11. }
  12.  
  13. void info(const char * msg) {
  14. g_msgLock.lock();
  15. std::cout << msg << 'n'; // don't flush
  16. g_msgLock.unlock();
  17. }
  18.  
  19. int main(int argc, char** argv) {
  20. info("Start message..");
  21.  
  22. std::vector<std::thread> threads;
  23. unsigned int threadCount = 10;
  24. threads.reserve(threadCount);
  25. std::vector<std::thread> threads;
  26.  
  27. { // Scope for locking all threads
  28.  
  29. std::lock_guard<std::shared_timed_mutex> lockAllThreads(g_testingLock); // RAII (scoped) lock
  30. for (unsigned int i = 0; i < threadCount; i++) {
  31. // Here we start the threads using lambdas
  32. threads.push_back(std::thread([&, i](){
  33. // Here we block and wait on lockAllThreads
  34. std::shared_lock<std::shared_timed_mutex> threadLock(g_testingLock);
  35. std::string msg = std::string("THREADED_TEST_INFO_MESSAGE: ") + std::to_string(i);
  36. info(msg.c_str());
  37. }));
  38. }
  39.  
  40. } // End of scope, lock is released, all threads continue now
  41.  
  42. for(auto& thread : threads){
  43. thread.join();
  44. }
  45. }
  46.  
  47. Start message..
  48. THREADED_TEST_INFO_MESSAGE: 9
  49. THREADED_TEST_INFO_MESSAGE: 5
  50. THREADED_TEST_INFO_MESSAGE: 3
  51. THREADED_TEST_INFO_MESSAGE: 1
  52. THREADED_TEST_INFO_MESSAGE: 4
  53. THREADED_TEST_INFO_MESSAGE: 0
  54. THREADED_TEST_INFO_MESSAGE: 8
  55. THREADED_TEST_INFO_MESSAGE: 7
Add Comment
Please, Sign In to add comment