使用 sigint 作为中断干净地退出 p 线程

时间:2021-06-16 13:48:55

标签: c linux multithreading signals raspberry-pi4

我目前正在研究 raspberry pi 并与它连接 ADC。 ADC 连续输出数字值。值的读取及其处理是在线程中启动和执行的,因此它应该永远运行。但是,为了(出于某种原因)从线程干净地退出,我想使用 SIGINT 信号处理程序,它会触发中断并更改 volatile 变量的状态。 伪程序如下:

volatile sig_atomic_t exitThread = 0;

void signalHandler(){
    exitThread = 1;
}

void SPI_Port0(){
    //initialisation of functions and variables
    
    while(!exitThread){
         //do the work
    }

    if(exitThread){
         pthread_exit(NULL);
    }
}

void main(){

     struct sigaction sa;
     memset(&sa, 0, sizeof(sa));
     sigemptyset(&sa.sa_mask);
     sa.sa_handler = signalHandler;
     
     sigaction(SIGINT, &sa, NULL);

     pthread_t SPI0,SPI3;
     pthread_create(&SPI0, NULL, SPI_Port0, NULL);
     pthread_create(&SPI3, NULL, SPI_Port1, NULL);

     pthread_join(SPI0, NULL);
     pthread_join(SPI3, NULL);

   //printing the results stored in arrays
   //the arrays is declared global
 }

有两个线程SPI_Port0和SPI_Port1 执行相同的实现,但在两个不同的 SPI 端口上,我希望这两个线程在按下 CTRL + C 时退出。我面临的问题是,整个程序都退出了。

有人能指出我正确的方向吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:-2)

变量和全局变量的修改不与子线程共享,因为它们是其他进程。

首先要捕捉信号: Catch Ctrl-C in C

那么,在信号中断时,必须杀死子线程:For pthread, How to kill child thread from the main thread

相关问题