首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用sem_open初始化信号量

使用sem_open初始化信号量
EN

Stack Overflow用户
提问于 2016-04-21 04:55:06
回答 1查看 13.4K关注 0票数 0

在我的生产者和消费者问题中,我使用sem_open初始化信号量。如何测试sem_open是否以正确的方式工作?

该程序可以编译,但当我运行该程序时,它什么也不打印。我测试了这个程序,发现问题可能与sem_open()有关。我发现如果我在程序中注释sem_open(),程序就会正确运行。

代码语言:javascript
运行
复制
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h> 
#include <unistd.h>

#define BUFFER_SIZE 10

int buffer[BUFFER_SIZE];
pthread_t pro_thread, con_thread;
pthread_mutex_t mutex;
int counter = 0;
sem_t  *empty, *full;

void print_buffer(int counter) {
    for (int i = 0; i < counter; i ++)
    {
        printf("*");
    }
    printf("\n");
}

void* producer(void* var) {
    int item;
    while(1) {
        item = rand() % 100 + 1;
        sem_wait(empty);
        pthread_mutex_lock(&mutex);

        while (counter == BUFFER_SIZE)
            ; // waiting

        if(counter < BUFFER_SIZE) {
            buffer[counter] = item;
            counter ++;
            printf("Producer: ");
            print_buffer(counter);
        }

        sleep(1);
        pthread_mutex_unlock(&mutex);
        sem_post(full);
    }
}

void* consumer(void* var) {
    int item;
    while(1) {
        sem_wait(full);
        pthread_mutex_lock(&mutex);

        while (counter == 0)
            ; // waiting

        if(counter > 0) {
            counter --;
            print_buffer(counter);
        }

        sleep(1);

        pthread_mutex_unlock(&mutex);
        sem_post(empty);
    }
}

int main(int argc, char *argv[]) {
    pthread_mutex_init(&mutex, NULL);
    empty = sem_open("/mysem", O_CREAT, 0644, BUFFER_SIZE);
    full = sem_open("/mysem", O_CREAT, 0644, 0);

    pthread_create(&pro_thread, NULL, producer, NULL);
    pthread_create(&con_thread, NULL, consumer, NULL);

    pthread_exit(NULL);

    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-21 06:49:15

sem_open man page中所述:

信号量由名称标识。

由于您的代码为两个sem_open调用提供了相同的name值(/mysem),因此它会导致为full和empty引用相同的信号量。这显然不是程序逻辑应该是什么。相反,为每个信号量打开不同的信号量。检查所有函数调用的返回值也是最佳实践。

代码语言:javascript
运行
复制
empty = sem_open("/empty_sem", O_CREAT, 0644, BUFFER_SIZE);
if (empty == SEM_FAILED) {
     perror("Failed to open semphore for empty");
     exit(-1);
}

full = sem_open("/full_sem", O_CREAT, 0644, 0);
if (full == SEM_FAILED) {
     sem_close(empty);
     perror("Failed to open semphore for full");
     exit(-1);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36755003

复制
相关文章

相似问题

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