Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created March 13, 2018 10:42
Show Gist options
  • Save rdeioris/553e2d19cd6c1183ac7a73d3e9771af1 to your computer and use it in GitHub Desktop.
Save rdeioris/553e2d19cd6c1183ac7a73d3e9771af1 to your computer and use it in GitHub Desktop.
#include <thread>
#include <mutex>
#include <iostream>
#include <list>
#include <condition_variable>
std::mutex mutex;
std::condition_variable cond_var;
thread_local int foo;
class Producer
{
public:
Producer(std::list<int> *queue)
{
this->queue = queue;
}
void Push(int value)
{
for(int i=0;i<10000;i++)
{
// lock the mutex (unlocked by the consumer)
mutex.lock();
this->queue->push_back(value);
// wake up the consumer
cond_var.notify_one();
// unlock the mutex, so the consumer will be truly reactivated
mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
private:
std::list<int> *queue;
};
class Consumer
{
public:
Consumer(std::list<int> *queue)
{
this->queue = queue;
}
int Dequeue()
{
if (this->queue->empty())
{
return -1;
}
int value = this->queue->front();
this->queue->pop_front();
return value;
}
private:
std::list<int> *queue;
};
int main(int argc, char **argv)
{
std::list<int> queue;
Producer producer(&queue);
Producer producer2(&queue);
Consumer consumer(&queue);
std::thread pusher1(&Producer::Push, &producer, 30);
std::thread pusher2(&Producer::Push, &producer2, 17);
std::unique_lock<std::mutex> locked(mutex);
for(;;)
{
// - release the mutex
// - inform the kernel that we want to be reactivated
// when cond_var changes
// - when the thread is reactivated -> reacquire the lock
cond_var.wait(locked);
int value = consumer.Dequeue();
if (value > -1)
{
std::cout << value << std::endl;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment