天天看點

一段簡單的Linux線程池代碼

實作web server時,通過建立一個線程池來并發處理用戶端的http請求,代碼如下:

for(i = 0; i < THREAD_POOL_SIZE; i++)

{

pthread_create(&thread_pool[i], NULL, (void*)&worker, (void*)i);

pthread_detach(thread_pool[i]);

}

線程并發處理如下:

void* worker(int n)

{

struct server_struct *request;

DebugMSG("Worker %d started!", n);

while(loop) // Global variable of "loop" indicates that server is running, if not set, quit

{

pthread_mutex_lock(&pool_mutex); // You should lock mutex before pthread_cond_wait call..

request = pop_request();

if (request == NULL) {

// No more jobs, go to sleep now

pthread_cond_wait(&new_request, &pool_mutex); // On pthread_cond_signal event pthread_cond_wait lock's mutex via pthread_mutex_lock

request = pop_request();

}

pthread_mutex_unlock(&pool_mutex); // so, you must unlock it.

if(request != NULL)

server(request);

pthread_cond_signal(&thread_free);

}

pthread_exit(NULL);

return NULL;

}

int push_request(struct server_struct* request)

{

int i, added = 0;

pthread_mutex_lock(&pool_mutex);

for(i = 0; (i < THREAD_POOL_SIZE)&&(!added); i++)

{

if(pool[i] == NULL)

{

pool[i] = request;

added = 1;

}

}

pthread_mutex_unlock(&pool_mutex);

if (added)

pthread_cond_signal(&new_request);

return added;

}

struct server_struct* pop_request()

{

int i;

struct server_struct *request = NULL;

for(i = 0; (i < THREAD_POOL_SIZE)&&(request == NULL); i++)

{

if(pool[i] != NULL)

{

request = pool[i];

pool[i] = NULL;

}

}

return request;

}

繼續閱讀