1) 定义存放已连接套接字描述符共享数组
2)创建线程池
3)等待用户连接
4)等待为之服务的客户描述符
#include <time.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
typedef struct {
pthread_t thread_tid;
long thread_count;
}Thread;
Thread *tptr;
int clifd[32],iget,iput;
pthread_mutex_t clifd_mutex;
pthread_cond_t clifd_cond;
void
web_child(int sockfd)
{
ssize_t n;
char buf[1024];
printf("web child\n");
while ( (n = read(sockfd, buf, 1024)) > 0)
write(sockfd, buf, n);
if (n < 0)
printf("str_echo: read error");
}
void *
thread_main(void * arg)
{
int connfd;
void web_child(int);
for(;;){
pthread_mutex_lock(&clifd_mutex);
printf("get mutex\n");
while(iget == iput){
int n;
if ((n=pthread_cond_wait(&clifd_cond, &clifd_mutex)) != 0)
{
printf("wait err\n");
return 0;
}
}
connfd = clifd[iget];
printf("connfd get \n");
if(++iget == 10)
iget = 0;
pthread_mutex_unlock(&clifd_mutex);
tptr[(int) arg].thread_count++;
web_child(connfd);
close(connfd);
}
}
void pthread_make(int i)
{
void *thread_main(void*);
pthread_create(&tptr[i].thread_tid, NULL, &thread_main, (void*)i);
}
int main(int argc, char** argv)
{
int i,sockfd, connfd;
void pthread_make(int);
socklen_t addrlen, clilen;
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("sock error\r\n");
return 0;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13000);
servaddr.sin_addr.s_addr = inet_addr("0.0.0.0");
if( bind(sockfd, (struct sockaddr* )&servaddr, sizeof(servaddr)) < 0)
{
printf("bind error\r\n");
return 0;
}
if(listen(sockfd, 10) < 0)
{
printf("listen error\r\n");
return 0;
}
int threadnum = 10;
iget = iput = 0;
tptr = calloc(threadnum , sizeof(Thread));
for(i = 0; i< 10; i++){
pthread_make(i);
}
for( ; ;)
{
connfd = accept(sockfd, NULL, NULL);
printf("accept sock %d \r\n",connfd);
pthread_mutex_lock(&clifd_mutex);
clifd[iput] = connfd;
iput++;
if(iput == 10)
iput = 0;
printf("iput iget %d %d \n",iput,iget);
int n;
if ( (n = pthread_cond_signal(&clifd_cond)) != 0){
printf("signal err\n");
return 0;
}
pthread_mutex_unlock(&clifd_mutex);
}
}
http://blog.chinaunix.net/uid-11572501-id-3456343.html
介绍了pthread_cond_signal与pthread_cond_wait详解