win32-pthreads未定义sem_init行为

时间:2018-09-24 01:45:01

标签: c multithreading

从我的帖子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);

0 个答案:

没有答案
相关问题