forked from p308945/MyNetWorkLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyThread.cpp
More file actions
102 lines (95 loc) · 1.85 KB
/
MyThread.cpp
File metadata and controls
102 lines (95 loc) · 1.85 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
98
99
100
101
102
/*************************************************************************
> File Name: MyThread.cpp
> Author: huangyun
> Mail: 895175589@qq.com
> Created Time: Fri 07 Aug 2015 12:25:55 AM
************************************************************************/
#include "MyThread.h"
#include <iostream>
#include <algorithm>
namespace MyNameSpace
{
MyThread::MyThread(bool j) : pid(0), state(0), mJoinable(j), complete(false)
{
}
void *MyThread::threadFun(void *arg)
{
MyThread *p = static_cast<MyThread *>(arg);
p->setState(1);
p->notifyStartSuccess();
std::cerr<<__FUNCTION__<<":"<<__LINE__<<" thread "<< "start!"<<std::endl;
p->run();
return NULL;
}
bool MyThread::start()
{
if (isStart())
{
return true;
}
if (!init())
{
std::cerr<<__FUNCTION__<<":"<<__LINE__<<" MyThread init fail!"<<std::endl;
return false;
}
int i = pthread_create(&pid, NULL, MyThread::threadFun, this);
if (i != 0)
{
std::cerr<<"pthread create error"<< std::endl;
return false;
}
mLock.lock();
while(state != 1)
{
mCond.wait();
}
mLock.unlock();
return true;
}
void MyThread::notifyStartSuccess()
{
mLock.lock();
mCond.notify();
mLock.unlock();
}
int MyThread::join()
{
return pthread_join(pid, NULL);
}
void MyThreadPool::putThread(MyThread* pThread)
{
mThreads.push_back(pThread);
}
void MyThreadPool::joinAll()
{
ContainerIt iter = mThreads.begin();
for (; iter != mThreads.end(); ++iter)
{
(*iter)->terminate();
if ((*iter)->isJoinAble())
{
(*iter)->join();
}
}
}
namespace
{
class DelFunctor
{
public:
void operator()(MyThread *thread)
{
if (NULL != thread)
{
delete thread;
}
}
};
DelFunctor delfun;
}
void MyThreadPool::delAllThread()
{
std::for_each(mThreads.begin(), mThreads.end(), delfun);
mThreads.clear();
}
}