【发布时间】:2015-06-29 15:03:45
【问题描述】:
我希望我的应用程序具有以下行为:当应用程序(服务器)正在等待来自另一个应用程序(客户端)的消息时,如果用户输入的时间过长,我希望能够退出。
因此,我必须从第三个线程启动两个线程:
WaitForClientMessageWaitForUserInput
使用pthread,我想我可以调用每个线程并给他们另一个的ID,所以如果他们结束,他们会取消另一个。但现在我发现它不起作用。
这是怎么做到的?我想这很简单,因为经常看到这种行为,但我不知道它是如何工作的。
编辑 这是一些描述我想象的通用代码。
void main_thread( void)
{
void * thread_rtn_val;
/* Parallel threads */
pthread_t thread_WaitForClientMessage;
pthread_t thread_WaitForUserInput;
/* Run Threads */
pthread_create(&thread_WaitForClientMessage, NULL, run_window, (void *)thread_sdp);
pthread_create(&thread_WaitForUserInput, NULL, run_client, (void *)arg_array);
}
void run_window( void)
{
/* Refresh screen and watch for user input */
for(...)
{
if(user press enter)
{
phtread_cancel(thread_WaitForClientMessage)
}
}
}
void run_client( void)
{
/* Wait for client message */
recv()...
phtread_cancel(thread_WaitForUserInput)
}
【问题讨论】:
-
能否请您提供您当前的代码和相应的语言标签?
-
当用户输入来自控制台时,客户端消息是否来自套接字?您可能可以在具有适当超时值的单个线程中使用
select或poll。 -
@Marvin 我会添加一些代码@NG。这里的线程位于更高层,我不想修改已经定义的套接字函数。
-
您可能应该使用 pthread_cond_t 作为一种方式来通知您的线程需要关闭。
标签: c++ multithreading