Skip to content

Commit 927cf2f

Browse files
committed
Create thread in constructor
- Create thread in constructor instead of separate function - Add new member to store pthread_t
1 parent 750ed0b commit 927cf2f

File tree

3 files changed

+6
-14
lines changed

3 files changed

+6
-14
lines changed

main.cpp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ int main(int argc, char **argv)
5555
//ThreadPool(N);
5656
//Create a Threadpool with N number of threads
5757
ThreadPool* myPool = new ThreadPool(2);
58-
myPool->initialize_thread();
5958

6059
//We will count time elapsed after initialize_thread()
6160
time_t t1=time(NULL);

threadpool.cpp

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
You should have received a copy of the GNU General Public License
1616
along with this program. If not, see <http://www.gnu.org/licenses/>.
1717
*/
18-
18+
#include <algorithm>
1919
#include <stdlib.h>
2020
#include "threadpool.h"
2121

@@ -26,7 +26,8 @@ pthread_mutex_t ThreadPool::_mutex_work_completion = PTHREAD_MUTEX_INITIALIZER;
2626

2727

2828
ThreadPool::ThreadPool(unsigned int num_thread)
29-
:_num_thread(num_thread)
29+
:_thread_pool(num_thread)
30+
,_num_thread(num_thread)
3031
,_worker_queue(num_thread, NULL)
3132
,_queue_size(num_thread)
3233
{
@@ -37,17 +38,10 @@ ThreadPool::ThreadPool(unsigned int num_thread)
3738
sem_init(&_available_work, 0, 0);
3839
sem_init(&_available_thread, 0, _queue_size);
3940
pthread_mutex_unlock(&_mutex_sync);
40-
}
4141

42-
void ThreadPool::initialize_thread()
43-
{
44-
for (unsigned int i = 0; i < _num_thread; ++i)
45-
{
46-
pthread_t tempThread;
47-
pthread_create(&tempThread, NULL, &ThreadPool::thread_execute, (void *) this );
48-
//threadIdVec[i] = tempThread;
42+
for (std::vector<pthread_t>::iterator i = _thread_pool.begin(); i != _thread_pool.end(); ++i) {
43+
pthread_create(&*i, NULL, &ThreadPool::thread_execute, this);
4944
}
50-
5145
}
5246

5347
ThreadPool::~ThreadPool()

threadpool.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,14 @@ class ThreadPool{
5151
bool assign_work(WorkerThread *worker);
5252
bool fetch_work(WorkerThread **worker);
5353

54-
void initialize_thread();
55-
5654
static void *thread_execute(void *param);
5755

5856
static pthread_mutex_t _mutex_sync;
5957
static pthread_mutex_t _mutex_work_completion;
6058

6159

6260
private:
61+
std::vector<pthread_t> _thread_pool;
6362
unsigned int _num_thread;
6463

6564
sem_t _available_work;

0 commit comments

Comments
 (0)