Created
June 1, 2022 17:50
-
-
Save ivankp/e9b4d3aa3eeecd7c1fd315f88c412023 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <thread> | |
| #include <mutex> | |
| #include <condition_variable> | |
| using std::cout, std::endl; | |
| std::mutex mx_writer; | |
| std::condition_variable | |
| cv_need_to_write, | |
| cv_writer_is_ready; | |
| bool | |
| need_to_write = false, | |
| writer_is_ready = true, | |
| end_writer = false; | |
| int data = -1; | |
| void writer() { | |
| for (;;) { | |
| { // acquire mutex | |
| std::unique_lock lock(mx_writer); | |
| // wait for main to request writing | |
| cv_need_to_write.wait(lock, []{ return need_to_write; }); | |
| if (end_writer) break; | |
| writer_is_ready = false; | |
| need_to_write = false, | |
| // writer does some work | |
| cout << "writer is working on " << data << endl; | |
| std::this_thread::sleep_for(std::chrono::milliseconds(2000)); | |
| cout << "writer is done" << endl; | |
| // writer is done | |
| writer_is_ready = true; | |
| // mutex is released | |
| } | |
| // notify main that writer is available | |
| cv_writer_is_ready.notify_one(); | |
| } | |
| } | |
| int main(int argc, char* argv[]) { | |
| std::thread worker(writer); | |
| for (int i=0; ++i <= 10000; ) { | |
| if (i%1000 == 0) { | |
| cout << "main counted to " << i << endl; | |
| { // acquire mutex | |
| std::unique_lock lock(mx_writer); | |
| // wait for writer to be done | |
| // before giving it more data | |
| cv_writer_is_ready.wait(lock, []{ return writer_is_ready; }); | |
| // writer is read | |
| // prepare data for it | |
| data = i; | |
| need_to_write = true; | |
| // mutex is released | |
| } | |
| // notify writer that work needs to be done | |
| cv_need_to_write.notify_one(); | |
| } | |
| } | |
| { // acquire mutex | |
| std::unique_lock lock(mx_writer); | |
| need_to_write = true; | |
| end_writer = true; | |
| cv_need_to_write.notify_one(); | |
| } | |
| worker.join(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment