我有一個客戶端/服務器方案。客戶端向服務器發送消息並立即啓動睡眠10秒的線程。主線程正在等待來自服務器的任何答覆。如果客戶得到任何答覆,在10秒內,它將指示計時器線程終止。我面臨的問題是線程不會自行終止,其他任何事情(通信,線程指示)都可以。這個代碼是:分段錯誤,使用pthread_exit()終止一個線程
服務器:
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";
}
這是做的正確方法是什麼我正在努力?
什麼阻止一個線程訪問'termin'而另一個線程正在修改呢? – 2014-12-01 20:34:51
應該有一些鎖。我的錯。 – user2831683 2014-12-01 20:56:11