标签:http os strong for 2014 代码 ar amp
下面是本人前不久刚挖出来的坑,热呼呼的还冒着气。
谁能发现坑在哪?
背景:
thread_main 函数:负责accept socket ,然后分发给worker thread。
thread_worker函数:负责消耗掉main thread 传递过来的线程。
关系图:
结构体设计:
struct thread_pool { pthread_mutex_t mutex; pthread_cond_t cond; pthread_t tids[MAX_THREADS]; int connfd; int ready; void (*process)(int s); };
thread_main 函数实现:
static void thread_main(struct thread_pool *pool, int s) { int connfd; for (;;) { /*get client sock*/ connfd = accept(s, NULL, NULL); fprintf(stderr, "current sock = %d\n", connfd); if (connfd == -1) { perror("accept"); break; } pthread_mutex_lock(&pool->mutex); printf("main: ready = %d\n", pool->ready); while (pool->ready == 1) { pthread_cond_wait(&pool->cond, &pool->mutex); } pool->connfd = connfd; pool->ready = 1; pthread_cond_signal(&pool->cond); pthread_mutex_unlock(&pool->mutex); } }
thread_worker 函数实现:
static void *thread_worker(void *arg) { struct thread_pool *p = (struct thread_pool *)arg; int connfd = -1; for (;;) { pthread_mutex_lock(&p->mutex); while (p->ready == 0) { pthread_cond_wait(&p->cond, &p->mutex); } connfd = p->connfd; p->ready = 0; printf("ready = %d\n", p->ready); pthread_mutex_unlock(&p->mutex); p->process(connfd); } return (void *)0; }
标签:http os strong for 2014 代码 ar amp
原文地址:http://my.oschina.net/guonaihong/blog/296044