我有一个客户端/服务器方案。客户端向服务器发送消息并立即启动一个休眠10秒的线程。主线程正在等待来自服务器的任何回复。如果客户端在10秒内收到任何回复,则表明计时器线程将终止。我面临的问题是线程不会自行终止,其他一切(通信,线程指示)都可以。代码是:
服务器:
if (recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, &slen) == -1)
cout<<"ERROR: recvfrom()";
cout<<"\nRECEIVED:\nClient : "
<<"\nData : "<<buf;
cout<<"\n\n";
cout<<"\nEnter data to send(Type exit and press enter to exit) : ";
cin.getline(buf, sizeof(buf), '\n');
if(strcmp(buf,"exit") == 0)
exit(0);
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, slen) == -1)
cout<<"ERROR: Problem sending data";
客户端:
cout<<"\nEnter data to send(Type exit and press enter to exit) :\n";
cin.getline(buf, sizeof(buf), '\n');
if(strcmp(buf,"exit") == 0)
exit(0);
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, addr_len) == -1)
cout<<"ERROR: Problem sending data";
pthread_t thread_id;
pthread_attr_t attr; // thread attribute
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&thread_id, &attr, thread_timer_process, NULL);
if(recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, &slen) == -1) cout<<"ERROR: recvfrom()";
else
termin = true;
cout<<"\nRECEIVED:\nServer : "
<<"\nData : "<<buf;
cout<<"\n\n";
静态变量和thread_timer_process():
static bool termin = false;
static int times = 10;
static const int INTERVAL_SEC = 1;
static void* thread_timer_process(void*)
{
int i=0;
cout<<"thread started\n";
signal(SIGINT, signal_callback_handler);
do
{
sleep(INTERVAL_SEC);
cout<<"In thread, i : "<<i<<"\n";
++i;
}
while(i<times && termin == false);
if(termin == true)
{
termin = false;
cout<<"--is exiting-\n";
}
pthread_exit(NULL);
cout<<"thread end\n";
}
这是我正在做的事情的正确方法吗?
答案 0 :(得分:1)
“这是我正在做的事情的正确方法吗?”
可能不是。为什么要明确地调用pthread_exit(NULL);
?
只是
cout << "thread end" << endl; // Note endl flushes the output
return NULL;
而不是
pthread_exit(NULL);
cout<<"thread end\n";
thread_timer_process()
函数中的应该可以正常工作,也可以修复此错误,因为您正在调用指定函数返回类型的未定义行为,但实际上没有返回任何内容 (the compiler should have issued a warning about this point, did it?) 子>
请参阅reference for pthread_exit
:
当首次调用main()的线程以外的线程从用于创建它的start例程返回时,对pthread_exit()进行隐式调用。函数的返回值用作线程的退出状态。
如果从取消清理处理程序或析构函数调用pthread_exit()的行为是由于对pthread_exit()的隐式或显式调用而调用的。 < /强>
另请参阅此处,了解有关pthread_exit()
行为和用法的更多提示: