我正在做我的项目,这是至关重要的是,一切都被正确地清理和所有缓冲日志消息保存到一个文件,等等。我正在从另一个线程调用exit,并且我正在考虑使用一个信号量来等待主线程中的清理在程序完全退出之前发生。问题是,当我从用atexit注册的退出处理程序调用sem_post时,sem_wait不会立即减少信号量,因此退出处理程序中的sem_wait将立即退出,因为信号量大于零。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
static sem_t sem;
void *do_work(void *arg) {
// if something fails
printf("Something failed!\n");
exit(1);
}
void exit_handler() {
sem_post(&sem); // wake up main thread
sem_wait(&sem); // wait for cleanup in main
sem_destroy(&sem);
}
int main() {
pthread_t worker_thread;
sem_init(&sem, 0, 0);
atexit(exit_handler);
pthread_create(&worker_thread, NULL, do_work, NULL);
sem_wait(&sem); // block this thread until work is done
// simulate some cleanup
usleep(1000000);
printf("This never gets called!\n");
sem_post(&sem); // destroy semaphore
}这个示例演示了我的问题。这个问题有什么解决办法吗?我不能将清理放在退出处理程序中,因为在我的实际程序中需要清理的主函数中有很多本地资源。
发布于 2015-12-30 15:20:07
在调用sem_wait()之后,无法控制哪个线程将从sem_post()返回。您需要使用两个信号量:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
static sem_t wakeupMain;
static sem_t cleanupDone;
void *do_work(void *arg) {
// if something fails
printf("Something failed!\n");
exit(1);
}
void exit_handler() {
sem_post(&wakeupMain); // wake up main thread
sem_wait(&cleanupDone); // wait for cleanup in main
sem_destroy(&wakeupMain);
sem_destroy(&cleanupDone);
}
int main() {
pthread_t worker_thread;
sem_init(&wakeupMain, 0, 0);
sem_init(&cleanupDone, 0, 0);
atexit(exit_handler);
pthread_create(&worker_thread, NULL, do_work, NULL);
sem_wait(&wakeupMain); // block this thread until work is done
// simulate some cleanup
usleep(1000000);
printf("This never gets called!\n");
sem_post(&cleanupDone); // destroy semaphore
}https://stackoverflow.com/questions/34531697
复制相似问题