并行线程互相停止

问题描述 投票:3回答:1

我希望我的应用程序具有以下行为:当应用程序(服务器)正在等待来自另一个应用程序(客户端)的消息时,如果来自用户的输入太长,我希望能够退出。

因此,我必须从第三个线程启动两个线程:

  1. WaitForClientMessage
  2. WaitForUserInput

使用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)
}
c++ multithreading
1个回答
0
投票

您是否为函数recv()尝试了非阻塞标志?

© www.soinside.com 2019 - 2024. All rights reserved.