Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Analog of https://gist.github.com/msg555/dd491078cf10dbabbe7b1cd142644910 in C++. Still not that fair but doesn't permanently starve threads.
#include <unistd.h>
#include <sys/time.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
using namespace std;
int max_dur = 0;
int counter = 2;
mutex mtx;
condition_variable cnd;
int mtime() {
struct timeval time_now{};
gettimeofday(&time_now, nullptr);
return (time_now.tv_sec * 1000) + (time_now.tv_usec / 1000);
}
void work(int id) {
for (int i = 0; i < 10000; i++) {
auto tm_start = mtime();
{
unique_lock<mutex> lck(mtx);
while (counter <= 0) {
cnd.wait(lck);
}
counter--;
}
auto tm_end = mtime();
usleep(5000);
{
unique_lock<mutex> lck(mtx);
auto dur = tm_end - tm_start;
if (dur > max_dur) {
max_dur = dur;
cout << "Longest wait " << id << ", " << dur << endl;
}
counter++;
cnd.notify_one();
}
}
}
int main() {
thread threads[10];
for (int i = 0; i < 10; i++) {
threads[i] = thread(work, i);
}
for (int i = 0; i < 10; i++) {
threads[i].join();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment