|
15 | 15 | You should have received a copy of the GNU General Public License |
16 | 16 | along with this program. If not, see <http://www.gnu.org/licenses/>. |
17 | 17 | */ |
18 | | -#include <algorithm> |
19 | | -#include <stdlib.h> |
20 | 18 | #include "threadpool.h" |
| 19 | +#include <stdlib.h> |
| 20 | +#include <errno.h> |
21 | 21 |
|
22 | 22 | using namespace std; |
23 | 23 |
|
24 | | -pthread_mutex_t ThreadPool::_mutex_sync = PTHREAD_MUTEX_INITIALIZER; |
25 | | -pthread_mutex_t ThreadPool::_mutex_work_completion = PTHREAD_MUTEX_INITIALIZER; |
26 | | - |
27 | 24 |
|
28 | 25 | ThreadPool::ThreadPool(unsigned int num_thread) |
29 | 26 | :_thread_pool(num_thread) |
30 | 27 | ,_num_thread(num_thread) |
31 | 28 | ,_worker_queue(num_thread, NULL) |
32 | 29 | ,_queue_size(num_thread) |
33 | 30 | { |
34 | | - pthread_mutex_lock(&_mutex_sync); |
35 | 31 | _top_index = 0; |
36 | 32 | _bottom_index = 0; |
37 | 33 | _incomplete_work = 0; |
38 | 34 | sem_init(&_available_work, 0, 0); |
39 | 35 | sem_init(&_available_thread, 0, _queue_size); |
40 | | - pthread_mutex_unlock(&_mutex_sync); |
| 36 | + |
| 37 | + init_mutex(&_mutex_sync); |
| 38 | + init_mutex(&_mutex_work_completion); |
41 | 39 |
|
42 | 40 | for (std::vector<pthread_t>::iterator i = _thread_pool.begin(); i != _thread_pool.end(); ++i) { |
43 | 41 | pthread_create(&*i, NULL, &ThreadPool::thread_execute, this); |
@@ -123,3 +121,38 @@ void *ThreadPool::thread_execute(void *param) |
123 | 121 | } |
124 | 122 | return 0; |
125 | 123 | } |
| 124 | + |
| 125 | +void ThreadPool::init_mutex(pthread_mutex_t* const mutex) |
| 126 | +{ |
| 127 | + int ret = pthread_mutex_init(mutex, NULL); |
| 128 | + switch (ret) { |
| 129 | + case 0: |
| 130 | + break; |
| 131 | + case EAGAIN: |
| 132 | + throw Error("EAGAIN returned by pthread_mutex_init()"); |
| 133 | + case ENOMEM: |
| 134 | + throw Error("ENOMEM returned by pthread_mutex_init()"); |
| 135 | + case EPERM: |
| 136 | + throw Error("EPERM returned by pthread_mutex_init()"); |
| 137 | + case EBUSY: |
| 138 | + throw Error("EBUSY returned by pthread_mutex_init()"); |
| 139 | + case EINVAL: |
| 140 | + throw Error("EINVAL returned by pthread_mutex_init()"); |
| 141 | + default: |
| 142 | + throw Error("UNKNOWN returned by pthread_mutex_init()"); |
| 143 | + }; |
| 144 | +} |
| 145 | + |
| 146 | +Error::Error(const char * what) |
| 147 | +:_what(what) |
| 148 | +{ |
| 149 | +} |
| 150 | + |
| 151 | +Error::~Error() throw() |
| 152 | +{ |
| 153 | +} |
| 154 | + |
| 155 | +const char* Error::what() const throw() |
| 156 | +{ |
| 157 | + return _what; |
| 158 | +} |
0 commit comments