并行线程互相停止

时间:2015-06-29 15:03:45

标签: c++ multithreading

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

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

  1. WaitForClientMessage
  2. WaitForUserInput
  3. 使用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)
    }
    

1 个答案:

答案 0 :(得分:0)

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

相关问题