-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcthread.cpp
More file actions
97 lines (78 loc) · 2.13 KB
/
cthread.cpp
File metadata and controls
97 lines (78 loc) · 2.13 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include "cthread.h"
using namespace std;
void CTask::SetData(void *data)
{
m_ptrData = data;
}
queue<CTask*>* CThreadPool::taskQueue2 = new queue<CTask*>[1];
queue<CTask*>* CThreadPool::taskQueue1 = new queue<CTask*>[1];
queue<CTask*>* CThreadPool::taskback = new queue<CTask*>[1];
pthread_mutex_t CThreadPool::m_threadMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t CThreadPool::m_taskMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t CThreadPool::m_threadCond = PTHREAD_COND_INITIALIZER;
pthread_cond_t CThreadPool::m_taskCond = PTHREAD_COND_INITIALIZER;
CThreadPool::CThreadPool(int threadNum)
{
this->m_threadNum = threadNum;
Create();
}
int CThreadPool::swapqueue(queue<CTask*>* &a, queue<CTask *>* &b)
{
queue<CTask *>*temp;
temp = a;
a = b;
b = temp;
return 0;
}
void *CThreadPool::ThreadFunc(void *arg)
{
pthread_t tid = pthread_self();
while (1)
{
CTask *task;
if (taskQueue1->empty() && !taskQueue2->empty())
{
swapqueue(taskQueue1, taskQueue2);
}
pthread_mutex_lock(&m_threadMutex);
if (taskQueue1->empty())
{
pthread_cond_wait(&m_threadCond, &m_threadMutex);
pthread_mutex_unlock(&m_threadMutex);
continue;
}
task = taskQueue1->front();
taskQueue1->pop();
pthread_mutex_unlock(&m_threadMutex);
task->Run();
pthread_mutex_lock(&m_taskMutex);
taskback->push(task);
pthread_mutex_unlock(&m_taskMutex);
}
return 0;
}
int CThreadPool::AddTask(CTask *task)
{
if (pthread_mutex_trylock(&m_threadMutex) == 0)
{
taskQueue1->push(task);
pthread_cond_signal(&m_threadCond);
cout << "add to queuel" << endl;
pthread_mutex_unlock(&m_threadMutex);
} else {
taskQueue2->push(task);
pthread_cond_signal(&m_threadCond);
cout << "add to queue2" << endl;
pthread_mutex_unlock(&m_threadMutex);
}
return 0;
}
CTask* CThreadPool::GetTaskBack()
{
CTask *task;
if (!taskback->empty())
{
task = taskback->front();
}
}