我试图创建一个并发的TCP服务器,它接受多个(N连接),其中N是已知的(例如N = 8)所以我试图创建一个prethreaded的TCP服务器。并发TCP服务器使用线程
.....
for(i=0;i<NUMBER_OF_CONNECTIONS;i++)
{
CreateThreads(i);
}
return 0;
}
//Create threads to handle the connection
void CreateThreads(int i)
{
pthread_create(&thread_tid[i], NULL, thread_function, (void *) i);
return;
}
void* thread_function(void *arg)
{
puts("In thread_function");
int client_soc,clilen;
struct sockaddr_in *clientaddr;
if((clientaddr = malloc(addrlen)) == NULL)
printf("malloc Error\n");
printf("thread %d starting\n", (int) arg);
while(1)
{
clilen = sizeof(struct sockaddr_in);
pthread_mutex_lock(&mlock);
puts("Calling accept \n");
if ((client_soc = accept(socket_desc, (struct sockaddr *)&clientaddr,(socklen_t*)&clilen)) < 0)
{
printf("accept error\n");
}
pthread_mutex_unlock(&mlock);
printf("Process Request...calling connection handler \n");
connection_handler(client_soc); /* process request */
close(client_soc);
}
}
//This will handle connection for each client
void *connection_handler(void *socket_desc)
{
//Receive and process.....
return 0;
}
在上面的代码线程创建和thread_function()被调用,但预期它不工作。程序在调用thread_function()之后结束,直到创建了几个线程。 我实际上想要创建“N”个线程数并等待客户端连接(使用accept())。一旦连接,我想接收/收集数据(或)发送命令等,这就是我有connection_handler()的原因,但我在此之前卡住。
任何人都可以尝试纠正thread_function()函数吗?我有点困在这里。谢谢。 UPDATE 该程序是基于 http://www.cse.fau.edu/~jie/research/publications/Publication_files/roussevwu.pdf 看看3.2节使用锁定和接受。
为什么投票结束。请在投票前添加评论。它有帮助! – m4n07 2013-02-21 14:54:16