首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在多线程环境中在sem_post之前调用sem_wait

在多线程环境中在sem_post之前调用sem_wait
EN

Stack Overflow用户
提问于 2021-01-05 08:33:10
回答 1查看 953关注 0票数 0

对于基于二进制信号量的实现,sem_post()函数的行为并不清楚。

在调用sem_wait()后调用sem_post()会发生什么情况?它能用吗?

代码示例:

线程1 :

代码语言:javascript
复制
do_something_critical()
sem_post();

线程2 :

代码语言:javascript
复制
sem_wait()
Proceed()

在这里,如果sem_post()是如何在调用sem_wait()之前被调用的,它会起作用吗?还是有必要在sem_wait()之前调用sem_post()

EN

回答 1

Stack Overflow用户

发布于 2021-01-05 12:09:10

sem_post()只是增加信号量并唤醒任何等待线程(如果有的话)。否则它什么也做不了。

sem_wait()只是减少信号量。只有当信号量的当前值为0时,调用方才会被阻塞。

下面是一个示例程序,其中主线程将信号量初始化为0,并调用sem_trywait()来验证信号量是否繁忙(即值为0)。然后,它调用sem_post()在创建线程之前释放信号量(即值为1)。线程调用sem_wait() (这会使信号量减少到0)并返回。主线程等待线程结束,并通过调用sem_trywait()验证信号量是否为0。

代码语言:javascript
复制
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>

static sem_t *sem;

void *thd_entry(void *p)
{
int rc;

  printf("Thread is starting...\n");

  // This decrements the semaphore
  rc = sem_wait(sem);
  if (0 != rc) {
    perror("sem_wait()");
    return NULL;
  }

  printf("Thread is exiting...\n");

  return NULL;

}

int main(int ac, char *av[])
{
int        rc;
pthread_t  thd;

  // Create a semaphore with an initial value set to 0
  sem = sem_open("/example", O_CREAT|O_RDWR, 0777, 0);
  if (sem == SEM_FAILED) {
    perror("sem_open()");
    return 1;
  }

  // After creation the value of the semaphore is 0
  rc = sem_trywait(sem);
  if (-1 == rc) {
    if (errno == EAGAIN) {
      printf("Semaphore is busy (i.e. value is 0)\n");
    } else {
      perror("sem_trywait()");
      return 1;
    }
  }

  // Increment the semaphore
  rc = sem_post(sem);
  if (0 != rc) {
    perror("sem_post()");
    return 1;
  }

  // Create a thread
  rc = pthread_create(&thd, NULL, thd_entry, 0);
  if (0 != rc) {
    errno = rc;
    perror("pthread_create()");
    return 1;
  }

  rc = pthread_join(thd, NULL);
  if (0 != rc) {
    errno = rc;
    perror("pthread_join()");
    return 1;
  }

  // The semaphore is 0 as the thread decremented it
  rc = sem_trywait(sem);
  if (-1 == rc) {
    if (errno == EAGAIN) {
      printf("Semaphore is busy (i.e. value is 0)\n");
    } else {
      perror("sem_trywait()");
      return 1;
    }
  }

  return 0;
}

以下是一次尝试:

代码语言:javascript
复制
$ ls -l /dev/shm
total 0
$ gcc sema.c -o sema -lpthread
$ ./sema 
Semaphore is busy (i.e. value is 0)
Thread is starting...
Thread is exiting...
Semaphore is busy (i.e. value is 0)
$ ls -l /dev/shm
total 4
-rwxrwxr-x 1 xxxxx xxxxx 32 janv.   5 16:24 sem.example
$ rm /dev/shm/sem.example
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65575437

复制
相关文章

相似问题

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