Following on from my post here, I have found that sem_init is failing for me whenever I pass a negative value as the value
parameter. However, when the sem_init below fails, the error number is set to 0, i.e. No Error
. I hope the solution to this problem can assist in the solution to my other problem.
Note: I am using pthreads-win32 on MS Visual Studio 2015, and have no compilation errors or warnings.
Includes and semaphore declarations:
// 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;
Code section:
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);