多线程下的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博客

相关推荐
通信小呆呆2 小时前
当波束搜索遇见信道编码和反向传播:两种让“粗搜索”不再犯错的新思路
人工智能·信息与通信·信号处理·信道编码·波束扫描
扣脑壳的FPGAer9 小时前
数字信号处理学习笔记--Chapter 1.4.1 时域采样定理基本概念
笔记·学习·信号处理
程序员-King.1 天前
【基础分析】—— 条件变量wait(lock, 谓词)
c++·c·多线程·条件变量
炘爚1 天前
C++多线程中Lambda核心用法与陷阱
多线程·系统编程
炘爚1 天前
多线程编程:线程与进程基础
多线程
炘爚1 天前
多线程编程:生产者消费者模型
多线程·系统编程·生产者消费者模型
Aaron15882 天前
RFSOC+VU13P+RK3588的核心优势与应用场景分析
嵌入式硬件·算法·matlab·fpga开发·信息与通信·信号处理·基带工程
Aaron15882 天前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
Ulyanov2 天前
ZeroMQ在分布式雷达仿真中的应用
分布式·python·信号处理·系统仿真·雷达电子对抗
fpcc3 天前
信号处理与AI中的卷积的关系
c++·人工智能·信号处理