We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <vector> #include <ctime> #include <cstdlib> std::mutex mtx; std::condition_variable cv; std::vector<int> data; bool has_data = false; void publisher() { while (true) { std::unique_lock<std::mutex> lock(mtx); int random_num = rand() % 100 + 1; data.push_back(random_num); has_data = true; std::cout << "Publisher published: " << random_num << std::endl; cv.notify_all(); lock.unlock(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } void subscriber() { while (true) { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return has_data; }); for (int num : data) { if (num % 2 == 0) { std::cout << "Subscriber received number: " << num << std::endl; } } data.clear(); has_data = false; lock.unlock(); } } int main() { srand(time(0)); std::thread pub(publisher); std::thread sub(subscriber); pub.join(); sub.join(); return 0; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
The text was updated successfully, but these errors were encountered: