Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <string>
- #include <mutex>
- struct ThreadData {
- std::string message;
- bool messageReady;
- std::mutex mutex;
- };
- void senderThread(ThreadData* data) {
- while (true) {
- using namespace std::chrono_literals;
- std::this_thread::sleep_for(100ms);
- std::cout << "Enter a message (type 'exit' to quit): ";
- std::getline(std::cin, data->message);
- {
- std::lock_guard<std::mutex> lock(data->mutex);
- data->messageReady = true;
- }
- if (data->message == "exit") {
- break;
- }
- }
- }
- void receiverThread(ThreadData* data) {
- while (true) {
- std::string messageToPrint;
- {
- std::lock_guard<std::mutex> lock(data->mutex);
- if (data->messageReady) {
- messageToPrint = data->message;
- data->messageReady = false;
- }
- }
- if (!messageToPrint.empty()) {
- std::cout << "Received message: " << messageToPrint << std::endl;
- if (messageToPrint == "exit") {
- break;
- }
- }
- }
- }
- int main() {
- ThreadData data;
- data.messageReady = false;
- std::thread sender(senderThread, &data);
- std::thread receiver(receiverThread, &data);
- sender.join();
- receiver.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement