-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
77 lines (55 loc) · 1.41 KB
/
ThreadPool.cpp
File metadata and controls
77 lines (55 loc) · 1.41 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
70
71
72
73
74
75
76
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include "ThreadPool.hpp"
pthread_mutex_t ThreadPool :: mPoolLock = PTHREAD_MUTEX_INITIALIZER;
queue<Job*> ThreadPool :: mJobQueue ;
ThreadPool :: ThreadPool()
{
}
ThreadPool :: ~ThreadPool()
{
}
void ThreadPool :: initialize(int numOfThreads)
{
mThreads = (pthread_t *)malloc(sizeof(pthread_t) * numOfThreads);
int i = 0 ;
for(i=0; i< numOfThreads; i++)
{
pthread_create(&mThreads[i], NULL, &run, NULL);
printf("created thread %u\n",(int)mThreads[i]);
}
}
void ThreadPool :: submitJob(void (*function_p)(int), int arg)
{
Job *j = new Job();
j->mFunction = function_p;
j->mArg = arg;
/* add the job to the jobQueue */
pthread_mutex_lock(&mPoolLock);
mJobQueue.push(j);
pthread_mutex_unlock(&mPoolLock);
}
void* ThreadPool :: run (void *arg)
{
while(1)
{
pthread_mutex_lock(&mPoolLock);
if(!mJobQueue.empty())
{
printf("\n");
printf("\nThread[%u] acquired the lock on jobQueue\n",(int)pthread_self());
Job *j = mJobQueue.front();
mJobQueue.pop();
printf("job found : %d %p %d\n",j->mArg,j->mFunction, (int)mJobQueue.size());
j->mFunction(j->mArg);
delete j;
j = NULL;
printf("Thread[%u] released the lock on jobQueue\n",(int)pthread_self());
printf("\n");
}
pthread_mutex_unlock(&mPoolLock);
}
}