1
0
Fork 0
This repository has been archived on 2021-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
uni-m.cds-adv-prog/ex10/threadpool.cc

55 lines
1.3 KiB
C++

// ThreadPool.cc
#include "threadpool.hh"
#include "shared_queue.hh"
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
void producer( const int id, SharedQueue<int>& q, int max_t, int max_n )
{
std::random_device d;
std::mt19937 mt(d());
std::uniform_int_distribution<> distr(0., max_t);
for ( int n = 0; n < max_n ; n++ )
{
n = distr(mt);
std::this_thread::sleep_for(std::chrono::milliseconds(n));
// Lock q so we can push a new element
std::unique_lock<std::mutex> lock(*q.mutex());
q.queue()->push(n);
// Notify one of the consumers
q.cv()->notify_one();
}
}
/*
void consumer( const int id, SharedQueue<int& q, int max_t, int max_n )
{
int b = 0;
for ( int n = 0; n < max_n ; n++ ){
{ // Scope the lock of the queue
std::unique_lock<std::mutex> q_lock(q_mutex);
while ( q.queue()->empty() ) {
// Wait until we get a signal from the condition variable
q_cv->wait(q_lock);
}
// Get a value and pop it off
b = q.front();
q.pop();
}
//std::cout << " -- Consumer " << id << " : " << b << std::endl;
// Slow down this thread to have a race between the consumers and the producers
// This only works after we have successfully read an int
std::this_thread::sleep_for(std::chrono::milliseconds(max_t));
}
}
*/