-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadsPool.cpp
More file actions
66 lines (56 loc) · 1.29 KB
/
ThreadsPool.cpp
File metadata and controls
66 lines (56 loc) · 1.29 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
//
// Created by haim on 26/01/17.
//
#include <zconf.h>
#include "ThreadsPool.h"
//start tasks.
void *startTasks(void *arg) {
ThreadsPool* tp = (ThreadsPool*) arg;
tp->runTasks();
return NULL;
}
//Constructor
ThreadsPool::ThreadsPool(int numOfThreads) : numOfThreads(numOfThreads) {
// TODO Auto-generated constructor stub
stop = false;
threads = new pthread_t[numOfThreads];
pthread_mutex_init(&lock, NULL);
for (int i = 0; i < numOfThreads; i++) {
pthread_create(threads + i, NULL, startTasks, this);
}
}
//run tasks.
void ThreadsPool::runTasks() {
while (!stop) {
pthread_mutex_lock(&lock);
if (tasks.empty()) {
pthread_mutex_unlock(&lock);
sleep(1);
} else {
Task* task = tasks.front();
tasks.pop();
pthread_mutex_unlock(&lock);
task->execute();
}
}
pthread_exit(NULL);
}
//empty pool.
void ThreadsPool::emptyPool() {
stop = true;
}
//add task.
void ThreadsPool::addTask(Task *task) {
tasks.push(task);
}
//distractor.
ThreadsPool::~ThreadsPool() {
pthread_mutex_destroy(&lock);
delete[] threads;
}
//join.
void ThreadsPool::join() {
for (int i = 0; i < numOfThreads; ++i) {
pthread_join(threads[i], NULL);
}
}