我无法在多线程程序(一台服务器,多个客户端)中终止服务器。
当计算当前连接的客户端数量的变量global_var
设置为0时,服务器应该终止,但不会终止。
我认为发生的事情是因为accept()
被阻塞了,所以代码永远不会在主循环中达到中断条件。
它正确地脱离了thread_func
,但随后在while
调用之前和打印accept()
之后在"Exiting thread_func"
循环内阻塞了。
volatile int finished = 0; // Gets set to 1 by catching SIGINT/SIGSTOP
int global_var = 0; // When it gets to 0, server should terminate
int server_fd;
void * thread_func(void* arg)
{
do_some_pre_stuff();
while(1)
{
if(!global_var)
{
close(server_fd);
finished = 1;
break;
}
if(recv(...) > 0)
{
do_more_stuff()
}
else
{
disconnect_client();
global_var--;
break;
}
}
free_more_ressources();
return NULL;
}
int main()
{
do_initial_stuff();
init_socket();
listen();
while (!finished)
{
if( (fd = accept(server_fd,...)) == -1)
exit(-1);
global_var++;
/* Some intermediate code */
if(!global_var)
break;
// Thread for the newly connected player
if(pthread_create(&thread_id[...], NULL, thread_func, (void*)some_arg)
exit(-1);
}
free_resources();
puts("Exiting thread_func");
}
我尝试了here中列出的建议,但没有成功(管道答案除外,不要试图弄乱管道)。
我是套接字编程的新手,但到目前为止我尝试过的方法看起来正确,但是没有一种解决方案(包括信号灯,pthread_cancel等)
PS:已实现同步,为便于阅读,在此省略