多线程下的signal信号处理

多线程中,信号在哪个线程中处理是不确定的,可能被任意一个线程处理

下边的代码可以验证该结论,多次Ctrl+c,会被不同的线程捕获此信号,并处理,最终每个线程死锁,阻塞在等待锁的状态

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
// 信号处理函数
void sigint_handler(int signum) {
    printf("Received SIGINT signal, %ld\n",pthread_self());
	printf("lock line %d\n",__LINE__);
	pthread_mutex_lock(&lock);
	//usleep(100);
	pthread_mutex_unlock(&lock);
	printf("unlock line %d\n",__LINE__);
}

// 线程函数
void* thread_func(void* arg) {
    while (1) { 
		printf("thread process, %ld\n",pthread_self());
		usleep(100000);
    }
    return NULL;
}

int main() {
    signal(SIGINT, sigint_handler);  // 注册SIGINT信号的处理函数
	printf("main process, %ld\n",pthread_self());
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, thread_func, NULL);  // 创建一个新线程
	pthread_create(&thread2, NULL, thread_func, NULL);  // 创建一个新线程
	while(1)
	{
		printf("lock line %d\n",__LINE__);		
		pthread_mutex_lock(&lock);
        usleep(100000);
		pthread_mutex_unlock(&lock);
		printf("unlock line %d\n",__LINE__);
	
	}
    pthread_join(thread1, NULL);  // 等待新线程退出
	pthread_join(thread2, NULL);  // 等待新线程退出
    return 0;
}

Linux多线程信号处理浅谈_linux信号处理函数在哪个线程_hdxbw-wq的博客-CSDN博客

相关推荐
苍煜8 小时前
多线程同步并行查询-CompletableFuture完整落地方案
多线程
hhl_483841041 天前
上海域格4G模块信号说明
linux·功能测试·物联网·信号处理·tcp
北京青翼科技1 天前
青翼科技基于XCVU13P FPGA的4路FMC接口高性能信号处理平台丨嵌入式智能平台 · 通用嵌入式平台丨FPGA信号处理板
fpga开发·信号处理·信号处理板·图形处理板卡·pcie数据处理板·fpga板卡
阿昭L1 天前
Windows中的I/O完成通知与事件内核对象
windows·多线程
阿冰冰呀2 天前
互联网大厂Java求职面试实录:谢飞机的“水货”之路
java·mybatis·dubbo·springboot·线程池·多线程·hashmap
代码中介商2 天前
Linux 信号处理与进程控制深度解析
linux·运维·信号处理
声光界2 天前
《信号处理赋能智能体音感知》
人工智能·音频·信号处理·声学
扣脑壳的FPGAer4 天前
傅里叶级数、傅里叶变换、Z变换、数字滤波器
fpga开发·信号处理
CoderMeijun6 天前
C++ 多线程进阶:Lambda、条件变量与死锁
c++·多线程·条件变量·lambda·死锁·生产者消费者
Adellle6 天前
Java 异步回调
java·开发语言·多线程