Skip to content

Instantly share code, notes, and snippets.

@osvimer
Created August 21, 2019 16:06
Show Gist options
  • Save osvimer/8c88cd0073a27b3129470af511ab88db to your computer and use it in GitHub Desktop.
Save osvimer/8c88cd0073a27b3129470af511ab88db to your computer and use it in GitHub Desktop.
#include <cstdlib>
#include <unistd.h>
#include <iostream>
#include <mutex>
#include <thread>
#include <queue>
#include <condition_variable>
std::mutex m;
std::condition_variable cv1; //write
std::condition_variable cv2; //read
std::queue<int> q;
const size_t kMaxSize = 10;
void producer(int id) {
while (1) {
usleep(10 * 1000);
std::unique_lock<std::mutex> lk(m);
if (q.size() < kMaxSize) {
int num= std::rand();
q.push(num);
printf("[producer:%d] (size:%d) num:%d\n", id, q.size(), num);
cv2.notify_all();
} else {
cv2.notify_all();
cv1.wait(lk, [] { return q.size() < kMaxSize; });
}
}
}
void consumer(int id) {
while (1) {
usleep(10 * 1000);
std::unique_lock<std::mutex> lk(m);
if (!q.empty()) {
int num = q.front();
q.pop();
printf("[consumer:%d] (size:%d) num:%d\n", id, q.size(), num);
cv1.notify_all();
} else {
cv1.notify_all();
cv2.wait(lk, [] { return !q.empty(); });
}
}
}
int main(int argc, const char* argv[]) {
std::srand(std::time(nullptr));
for (int i = 0; i < kMaxSize; i += 2) {
std::thread t1(producer, i);
std::thread t2(consumer, i + 1);
t1.detach();
t2.detach();
}
while(1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment