首页 > 解决方案 > win32-pthreads 未定义的 sem_init 行为

问题描述

继我的帖子here之后,我发现每当我将负值作为value参数传递时,sem_init 都会失败。但是,当下面的 sem_init 失败时,错误号设置为 0,即No Error. 我希望这个问题的解决方案可以帮助解决我的其他问题。

注意:我在 MS Visual Studio 2015 上使用 pthreads-win32,没有编译错误或警告。

包含和信号量声明:

// pthread-win32 defines
#ifdef _WIN32

#define HAVE_STRUCT_TIMESPEC

#endif // _WIN32

// Includes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <pthread.h>
#include <semaphore.h>

#include "include.h"

// Platform includes
#ifdef _WIN32

#include <fcntl.h>
#include <sched.h>
#include <windows.h>

#else

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>

#endif  // _WIN32

// Globals
sem_t queue_semaphore;
sem_t test_mode_semaphore;

代码部分:

if (sem_init(&test_mode_semaphore, 0, -2) == -1) {
    perror("Error initialising semaphore");           // Error occurring here
}

for (int i = 0; i < 3; i++) {

    /* Start Critical Region */
    pthread_mutex_lock(&mutex_qq);

    //...

    // Increment value of queue_semaphore by 1 
    if (sem_post(&queue_semaphore) == -1) {
        perror("Error incrementing semaphore");
    }

    /* End Critical Region */
    pthread_mutex_unlock(&mutex_qq);
}

// Wait
if (sem_wait(&test_mode_semaphore)) {
    perror("Error waiting for semaphore");
}

// Destroy test mode semaphore
sem_destroy(&test_mode_semaphore);

标签: cmultithreading

解决方案


推荐阅读