0

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);
  • It makes no sense to initialize a semaphore with a negative count. Why would you expect it to not fail? – Shawn Sep 24 '18 at 02:24
  • @Shawn I thought it was OK. My intention is that I initialize it to `-2`, as three other thread processes will `post()`. Therefore when they post upon completion, the `sem_wait` would pass since it would be above zero, i.e. 1. How else would I implement that? Since I am only `waiting` in the primary thread. It works perfectly well in normal pthreads in Unix. Yet if this is my problem please elaborate why. – wizardstack Sep 24 '18 at 02:37
  • Sounds like you need a barrier. – Shawn Sep 24 '18 at 03:10
  • @Shawn Indeed, that seems like a solution. I shall try it out now thank you – wizardstack Sep 24 '18 at 03:33
  • @Shawn A barrier did the job. Thanks again! – wizardstack Sep 24 '18 at 04:01
  • @Shawn Is defining semaphores with a value of 0 OK? – wizardstack Sep 24 '18 at 04:07

0 Answers0