-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapqueue.cc
More file actions
69 lines (59 loc) · 1.5 KB
/
mapqueue.cc
File metadata and controls
69 lines (59 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <queue>
#include <mutex>
using namespace std;
void takeJobs(int threadNum, queue<int>* jobQueue, mutex* jobLock)
{
while (1)
{
jobLock->lock();
if (!jobQueue->empty())
{
int jobLength = jobQueue->front();
jobQueue->pop();
printf("%i took a job of length %i. Number of jobs left: %i\n", threadNum, jobLength, (int)jobQueue->size());
jobLock->unlock();
this_thread::sleep_for(std::chrono::seconds(jobLength));
printf("%i finished its job.\n", threadNum);
} else{
jobLock->unlock();
}
}
}
void makeJobs(int threadNum, queue<int>* jobQueue, mutex* jobLock)
{
while (1)
{
int jobLength = rand()%5 + 1;
jobLock->lock();
jobQueue->push(jobLength);
printf("%i created a job of length %i. Number of jobs left: %i\n", threadNum, jobLength, (int)jobQueue->size());
jobLock->unlock();
this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main(int argc, char** argv)
{
int numConsumers = 1;
if(argc > 1)
{
numConsumers = atoi(argv[1]);
}
queue<int> jobQueue;
mutex jobLock;
thread producer = thread(makeJobs, 0, &jobQueue, &jobLock);
thread* consumers = new thread[numConsumers];
for(int i = 0; i < numConsumers; i++)
{
consumers[i] = thread(takeJobs, i + 1, &jobQueue, &jobLock);
}
producer.join();
for(int i = 0; i < numConsumers; i++)
{
consumers[i].join();
}
}