Advertisement
STANAANDREY

intel threads

Oct 21st, 2023 (edited)
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <string>
  4. #include <mutex>
  5.  
  6. struct ThreadData {
  7.     std::string message;
  8.     bool messageReady;
  9.     std::mutex mutex;
  10. };
  11.  
  12. void senderThread(ThreadData* data) {
  13.     while (true) {
  14.         using namespace std::chrono_literals;
  15.         std::this_thread::sleep_for(100ms);
  16.         std::cout << "Enter a message (type 'exit' to quit): ";
  17.         std::getline(std::cin, data->message);
  18.  
  19.         {
  20.             std::lock_guard<std::mutex> lock(data->mutex);
  21.             data->messageReady = true;
  22.         }
  23.  
  24.         if (data->message == "exit") {
  25.             break;
  26.         }
  27.     }
  28. }
  29.  
  30. void receiverThread(ThreadData* data) {
  31.     while (true) {
  32.         std::string messageToPrint;
  33.  
  34.         {
  35.             std::lock_guard<std::mutex> lock(data->mutex);
  36.             if (data->messageReady) {
  37.                 messageToPrint = data->message;
  38.                 data->messageReady = false;
  39.             }
  40.         }
  41.  
  42.         if (!messageToPrint.empty()) {
  43.             std::cout << "Received message: " << messageToPrint << std::endl;
  44.             if (messageToPrint == "exit") {
  45.                 break;
  46.             }
  47.         }
  48.     }
  49. }
  50.  
  51. int main() {
  52.     ThreadData data;
  53.     data.messageReady = false;
  54.  
  55.     std::thread sender(senderThread, &data);
  56.     std::thread receiver(receiverThread, &data);
  57.  
  58.     sender.join();
  59.     receiver.join();
  60.  
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement