Skip to content

Instantly share code, notes, and snippets.

@Determinant
Last active October 28, 2019 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Determinant/c59fafc72ea073d4f286150e310b915b to your computer and use it in GitHub Desktop.
Save Determinant/c59fafc72ea073d4f286150e310b915b to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <unistd.h>
std::atomic<bool> processing;
bool avail;
int result;
std::mutex m;
std::condition_variable cv;
// this assumes the thread already holds the lock
void process_value(int thread_name) {
printf("%d: ok I'll do the math\n", thread_name);
usleep(500000);
result = 1;
printf("%d: done\n", thread_name);
}
void get_value(int thread_name) {
if (!processing.exchange(true, std::memory_order_acq_rel))
{
process_value(thread_name);
std::lock_guard<std::mutex> l(m);
avail = true;
cv.notify_all();
}
else
{
std::unique_lock<std::mutex> l(m);
cv.wait(l, []{ return avail; });
}
printf("%d: I think the value is %d\n", thread_name, result);
}
int main() {
int n = 100;
srand(time(0));
std::vector<std::thread> workers;
for (int i = 0; i < n; i++)
workers.push_back(std::thread([=]() {
usleep(rand() % 10 * 10000);
get_value(i);
}));
for (auto &w: workers)
w.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment