Created
April 13, 2017 17:28
-
-
Save victusfate/e796f7110bd7b345affd6949a98cb4dc to your computer and use it in GitHub Desktop.
simple producer consumer in c++11 using threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
#include <thread> | |
#include <mutex> | |
#include <vector> | |
#include <unordered_map> | |
#include <queue> | |
#include <chrono> | |
using namespace std; | |
unsigned int prodVal = 0; | |
unsigned int stopVal = 1000; | |
unsigned int NProducers = 2; | |
unsigned int NConsumers = 5; | |
queue<unsigned int> taskQueue; | |
unordered_map<unsigned int, unsigned int> resultMap; | |
mutex taskQueueMutex; | |
mutex resultMutex; | |
thread producer() { | |
thread threadObj([](){ | |
while (prodVal < stopVal) { | |
unsigned int val = prodVal++; | |
unsigned int sleepMS = ((double) rand() / (RAND_MAX)) * 10; | |
taskQueueMutex.lock(); | |
taskQueue.push(val); | |
cout << "producer " << this_thread::get_id() << " val " << val << " sleepMS " << sleepMS << endl; | |
taskQueueMutex.unlock(); | |
this_thread::sleep_for(chrono::milliseconds(sleepMS)); | |
} | |
}); | |
return threadObj; | |
} | |
thread consumer() { | |
thread threadObj([](){ | |
while (1) { | |
unsigned int sleepMS = ((double) rand() / (RAND_MAX)) * 10 * (double)NConsumers/(double)NProducers; | |
if (taskQueue.size() > 0) { | |
taskQueueMutex.lock(); | |
unsigned int val = taskQueue.front(); | |
taskQueue.pop(); | |
taskQueueMutex.unlock(); | |
resultMutex.lock(); | |
unsigned int result = val * val; | |
resultMap[val] = result; | |
cout << "consumer " << this_thread::get_id() << " val " << val << " result " << result << " sleepMS " << sleepMS << endl; | |
resultMutex.unlock(); | |
} | |
else if (prodVal >= stopVal) { | |
break; | |
} | |
this_thread::sleep_for(chrono::milliseconds(sleepMS)); | |
} | |
}); | |
return threadObj; | |
} | |
int main() { | |
vector<thread> producers; | |
for (unsigned int i = 0;i < NProducers;i++) { | |
producers.push_back(producer()); | |
} | |
vector<thread> consumers; | |
for (unsigned int i = 0;i < NConsumers;i++) { | |
consumers.push_back(consumer()); | |
} | |
for (auto&& pThread : producers ) { | |
pThread.join(); | |
} | |
for (auto&& pThread : consumers ) { | |
pThread.join(); | |
} | |
cout << "results\n"; | |
for (unsigned int i = 0; i < stopVal;i++) { | |
auto val = resultMap.find(i); | |
if (val == resultMap.end()) { | |
cout << i << ":notFound" << endl; | |
} | |
else { | |
cout << i << ":" << resultMap[i] << endl; | |
} | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment