SHARE
TWEET

Untitled

a guest Nov 17th, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <thread>
  3. #include <string>
  4. #include <mutex>
  5. #include <memory>
  6. #include <vector>
  7.  
  8. std::mutex consoleMtx;
  9.  
  10. void writeString(const std::string &string)
  11. {
  12.     consoleMtx.lock();
  13.     std::cout << string << std::endl;
  14.     consoleMtx.unlock();
  15. }
  16.  
  17. std::vector<std::thread> startThreads()
  18. {
  19.     std::shared_ptr<std::string> sharedString(new std::string("I can't believe you've done this")); // When does this string get destroyed? Don't know, don't care.
  20.     std::vector<std::thread> tp;
  21.     for(unsigned char i = 0; i < 4; ++i)
  22.     {
  23.         tp.emplace_back([](std::shared_ptr<std::string> string){writeString(*string);}, sharedString);
  24.     }
  25.     return tp;
  26. }
  27.  
  28. int main()
  29. {
  30.     auto tp = startThreads();
  31.     for(auto &t : tp)
  32.     {
  33.         t.join();
  34.     }
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top