pthread数组 - 线程仍处于活动状态?

时间:2014-12-17 14:31:12

标签: c pthreads

服务器创建使用

处理客户端的线程
if (pthread_create(&array_of_threads[index], NULL, &thread_function, &argument) != 0)
    signal error

线程在客户完成后自行结束。

但是,可能存在必须退出服务器的情况 - 例如在收到信号或特殊消息后。

当发生这种情况时,我想在正在运行的线程上调用pthread_cancel(那些将调用pthread_cleanup并释放资源,告诉客户“关闭等等”。< / p>

有没有办法做到这一点,没有额外的bool数组告诉天气thread_array中的索引正在运行?

2 个答案:

答案 0 :(得分:0)

我提供了一个代码骨架,我用它来做这样的事情。请任何看到问题评论并建议改进此答案的人

#include <signal.h>

 int SIG=0;

 // Prototypes
 void SIG_HANDLER(int signum);


int main(void){

     // Register signal and handler
     signal(SIGINT,SIG_HANDLER);

     while(!SIG){
         // DO everything here
         // Such as creating thread for clients
         // Remember you create Detached threads 
     }

    // On SIGNAL clean main function's (main Thread's) resources

    return 0;
}

 // Thread function - Handle individual clients
void* handle_client(void * arg){

    while(!SIG){
      // Handle client here
    }
    return NULL;
}


// Signal handler
 void SIG_HANDLER(int signum){
    int i;
    printf("\nCaught signal : %d \n",signum);
    SIG=1;

    // close all sockets available for clients (end running threads)

    sleep(1);

    exit(signum);
}

注意 - 您需要semaphore来实现此类和实施

指南 - http://www.csc.villanova.edu/~mdamian/threads/posixsem.html

答案 1 :(得分:0)

  

有没有办法在没有额外的bool数组的情况下这样做,告诉天气,在thread_array中的索引正在运行?

没有

相关问题