How to let a thread which blocks on recv() exit gracefully?

后端 未结 7 1808
暗喜
暗喜 2020-12-11 17:27

There is a thread likes this:

{  
    ......    
    while (1)
    {
        recv(socket, buffer, sizeof(buffer), 0);
        ......
    }
    close(socket         


        
7条回答
  •  一生所求
    2020-12-11 17:52

    Declare a global exit flag:

    int bExit = 0;
    

    Let the cirtical parts test it:

     while(1)
     {
       ssize_t result = recv(socket, buffer, sizeof(buffer), 0);
       if ((-1 == result) && (EINTR == error) && bExit) 
       {
         break;
       }
    
       ...
     }
    

    To break your reader, first set the exit flag

    bExit = 1;
    

    then send a signal to the reader thread

    pthread_kill(pthreadReader, SIGUSR1);
    

    Note: What I left out in this example is the protection of bExit against concurrent access.

    This might be achieved by using a mutex or an appropriate declaration.

提交回复
热议问题