Skip to content

Instantly share code, notes, and snippets.

@msg555
Created February 21, 2022 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msg555/14d8029b910704a42d372004d3afa465 to your computer and use it in GitHub Desktop.
Save msg555/14d8029b910704a42d372004d3afa465 to your computer and use it in GitHub Desktop.
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