设计思路
- 信号处理函数:注册一个信号处理函数来捕获
SIGTERM
信号。在这个函数中,设置一个全局标志,表示程序需要终止。
- 线程协作:每个线程在运行过程中,需要定期检查这个全局标志。当标志被设置时,线程应有序地清理自己的工作并退出。
- 资源管理:对于动态分配的资源,每个线程负责释放自己分配的资源。主线程可以负责释放那些全局的动态资源,如打开的文件描述符等。
关键代码片段
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
// 全局标志,用于通知线程终止
volatile sig_atomic_t stop = 0;
// 模拟线程函数
void* thread_function(void* arg) {
while (!stop) {
// 线程工作
printf("Thread is working...\n");
sleep(1);
}
// 释放线程分配的资源,这里假设分配了内存
int* data = (int*)arg;
free(data);
printf("Thread exiting...\n");
return NULL;
}
// 信号处理函数
void sigterm_handler(int signum) {
stop = 1;
printf("Received SIGTERM, preparing to stop threads...\n");
}
int main() {
pthread_t thread;
int* data = (int*)malloc(sizeof(int));
if (data == NULL) {
perror("malloc");
return 1;
}
// 注册信号处理函数
struct sigaction sa;
sa.sa_handler = sigterm_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
// 创建线程
if (pthread_create(&thread, NULL, thread_function, data) != 0) {
perror("pthread_create");
free(data);
return 1;
}
// 等待线程结束
pthread_join(thread, NULL);
// 主线程释放全局资源,这里假设打开了一个文件描述符
FILE* file = fopen("test.txt", "r");
if (file != NULL) {
fclose(file);
}
printf("All threads stopped, resources released. Exiting...\n");
return 0;
}