parent
b0c9fefa9b
commit
0bac4dbfd9
@ -1,34 +1,54 @@ |
|||||||
#include <thread> |
#include <condition_variable> |
||||||
#include <fmt/core.h> |
|
||||||
#include <chrono> |
|
||||||
#include <iostream> |
|
||||||
#include <thread> |
|
||||||
#include <utility> |
|
||||||
#include <iostream> |
#include <iostream> |
||||||
#include <mutex> |
#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; |
void worker_thread() |
||||||
std::mutex counter_mutex; |
{ |
||||||
|
// 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() { |
// send data back to main()
|
||||||
for (int i = 0; i < 5; ++i) |
processed = true; |
||||||
{ |
std::cout << "Worker thread signals data processing completed\n"; |
||||||
std::lock_guard<std::mutex> lock(counter_mutex); |
|
||||||
std::this_thread::sleep_for(100ms); |
// manual unlocking is done before notifying, to avoid waking up
|
||||||
std::cout << "Thread 1 executing\n"; |
// the waiting thread only to block again (see notify_one for details)
|
||||||
++counter; |
lk.unlock(); |
||||||
} |
cv.notify_one(); |
||||||
} |
} |
||||||
|
|
||||||
int main() |
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) { |
// wait for the worker
|
||||||
std::lock_guard<std::mutex> lock(counter_mutex); |
{ |
||||||
std::cout << "counter is " << counter << std::endl; |
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