/实现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;
}
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;
}