parent
b0c9fefa9b
commit
0bac4dbfd9
@ -1,34 +1,54 @@ |
||||
#include <thread> |
||||
#include <fmt/core.h> |
||||
#include <chrono> |
||||
#include <iostream> |
||||
#include <thread> |
||||
#include <utility> |
||||
#include <condition_variable> |
||||
#include <iostream> |
||||
#include <mutex> |
||||
#include <string> |
||||
#include <thread> |
||||
|
||||
using namespace std::chrono_literals; |
||||
std::mutex m; |
||||
std::condition_variable cv; |
||||
std::string data; |
||||
bool ready = false; |
||||
bool processed = false; |
||||
|
||||
std::atomic_int counter = 0; |
||||
std::mutex counter_mutex; |
||||
void worker_thread() |
||||
{ |
||||
// wait until main() sends data
|
||||
std::unique_lock lk(m); |
||||
cv.wait(lk, []{ return ready; }); |
||||
|
||||
// after the wait, we own the lock
|
||||
std::cout << "Worker thread is processing data\n"; |
||||
data += " after processing"; |
||||
|
||||
void locked_counter() { |
||||
for (int i = 0; i < 5; ++i) |
||||
{ |
||||
std::lock_guard<std::mutex> lock(counter_mutex); |
||||
std::this_thread::sleep_for(100ms); |
||||
std::cout << "Thread 1 executing\n"; |
||||
++counter; |
||||
} |
||||
// send data back to main()
|
||||
processed = true; |
||||
std::cout << "Worker thread signals data processing completed\n"; |
||||
|
||||
// manual unlocking is done before notifying, to avoid waking up
|
||||
// the waiting thread only to block again (see notify_one for details)
|
||||
lk.unlock(); |
||||
cv.notify_one(); |
||||
} |
||||
|
||||
int main() |
||||
{ |
||||
std::jthread t2(locked_counter); // pass by value
|
||||
std::thread worker(worker_thread); |
||||
|
||||
data = "Example data"; |
||||
// send data to the worker thread
|
||||
{ |
||||
std::lock_guard lk(m); |
||||
ready = true; |
||||
std::cout << "main() signals data ready for processing\n"; |
||||
} |
||||
cv.notify_one(); |
||||
|
||||
for(int i = 0; i < 5; ++i) { |
||||
std::lock_guard<std::mutex> lock(counter_mutex); |
||||
std::cout << "counter is " << counter << std::endl; |
||||
// wait for the worker
|
||||
{ |
||||
std::unique_lock lk(m); |
||||
cv.wait(lk, []{ return processed; }); |
||||
} |
||||
std::cout << "Back in main(), data = " << data << '\n'; |
||||
|
||||
worker.join(); |
||||
} |
||||
|
Loading…
Reference in new issue