首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sem_post不对其他线程中的sem_wait调用排序。

sem_post不对其他线程中的sem_wait调用排序。
EN

Stack Overflow用户
提问于 2015-12-30 14:47:06
回答 1查看 2.7K关注 0票数 1

我正在做我的项目,这是至关重要的是,一切都被正确地清理和所有缓冲日志消息保存到一个文件,等等。我正在从另一个线程调用exit,并且我正在考虑使用一个信号量来等待主线程中的清理在程序完全退出之前发生。问题是,当我从用atexit注册的退出处理程序调用sem_post时,sem_wait不会立即减少信号量,因此退出处理程序中的sem_wait将立即退出,因为信号量大于零。

代码语言:javascript
复制
#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
}

这个示例演示了我的问题。这个问题有什么解决办法吗?我不能将清理放在退出处理程序中,因为在我的实际程序中需要清理的主函数中有很多本地资源。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-30 15:20:07

在调用sem_wait()之后,无法控制哪个线程将从sem_post()返回。您需要使用两个信号量:

代码语言:javascript
复制
#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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34531697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档