设计思路
- 信号处理函数注册:在主线程中使用
signal
或sigaction
函数注册SIGTERM信号的处理函数。
- 线程同步:使用互斥锁(mutex)来保护共享资源,确保在信号处理函数和子线程访问共享资源时不会产生竞争条件。
- 终止子线程:在信号处理函数中,设置一个标志位,通知所有子线程需要终止。子线程在合适的时机(如循环中检查标志位)检查这个标志位,然后安全地退出。
- 清理工作:主线程在所有子线程退出后,进行清理工作,如释放资源等,然后退出。
关键代码片段
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int should_exit = 0;
// 子线程函数
void* thread_function(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (should_exit) {
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
// 子线程工作内容
printf("子线程正在工作...\n");
sleep(1);
}
pthread_exit(NULL);
}
// SIGTERM信号处理函数
void signal_handler(int signum) {
pthread_mutex_lock(&mutex);
should_exit = 1;
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_t threads[10];
int i;
// 注册SIGTERM信号处理函数
signal(SIGTERM, signal_handler);
// 创建子线程
for (i = 0; i < 10; i++) {
if (pthread_create(&threads[i], NULL, thread_function, NULL) != 0) {
perror("pthread_create");
return 1;
}
}
// 等待信号
while (!should_exit) {
sleep(1);
}
// 等待所有子线程结束
for (i = 0; i < 10; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("pthread_join");
return 1;
}
}
// 主线程清理工作
printf("主线程进行清理工作...\n");
pthread_mutex_destroy(&mutex);
return 0;
}