Skip to content

Commit 35e19bb

Browse files
committed
Add error handling for pthread_create()
1 parent 4053d7b commit 35e19bb

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

threadpool.cpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,9 @@
1818
#include "threadpool.h"
1919

2020
#include <iostream>
21-
2221
#include <cassert>
23-
#include <stdlib.h>
24-
#include <errno.h>
2522

26-
using namespace std;
23+
#include <errno.h>
2724

2825
class ScopedMutex {
2926
public:
@@ -80,18 +77,34 @@ ThreadPool::ThreadPool(unsigned int num_thread)
8077
init_mutex(&_work_mutex);
8178

8279
for (std::vector<pthread_t>::iterator i = _thread_pool.begin(); i != _thread_pool.end(); ++i) {
83-
pthread_create(&*i, NULL, &ThreadPool::thread_execute, this);
80+
int ret = pthread_create(&*i, NULL, &ThreadPool::thread_execute, this);
81+
switch (ret) {
82+
case 0:
83+
break;
84+
case EAGAIN:
85+
throw Error("EAGAIN returned by pthread_create()");
86+
case EINVAL:
87+
throw Error("EINVAL returned by pthread_create()");
88+
case EPERM:
89+
throw Error("EPERM returned by pthread_create()");
90+
default:
91+
throw Error("UNKNOWN returned by pthread_create()");
92+
}
8493
}
8594
}
8695

8796
ThreadPool::~ThreadPool()
8897
{
98+
/*
99+
* All failures are ignored in destructor.
100+
*/
101+
89102
int ret = 0;
90103
// make sure all thread finish its jobs.
91104
for (unsigned int i = 0; i < _thread_pool.size(); ++i) {
92105
ret = sem_timedwait(&_available_work, &DESTROY_TIMEOUT);
93106
if (0 != ret) {
94-
std::cerr << "Timeout, stop ThreadPool with work" << std::endl;
107+
std::cerr << "Timeout, stop ThreadPool" << std::endl;
95108
break;
96109
}
97110
}

0 commit comments

Comments
 (0)