I am trying to create an array of semaphores, however my code is not running correctly so I am hoping to get some feedback on whether I am doing this correct.
Creating the semaphore array as a global variable, I have:
sem_t sems [10] = {};
Then filling the array (in main):
sem_t sem0;
sems[0] = sem0;
sem_t sem1;
sems[1] = sem1;
sem_t sem2;
sems[2] = sem2;
...
And finally, initalizing the semaphores:
sem_init(&sem0, 0, 1);
sem_init(&sem1, 0, 0);
sem_init(&sem2, 0, 0);
...
I am referring to each semaphore by using &sems[threadID]
, where each threadID is between 0 and 9. It seems to work, but sem_wait() is being ignored and threads are running when they should be waiting. I am not great at C and am hoping for any indication of what I am doing wrong. Thank you in advance.
CodePudding user response:
I don't know what you expect the middle part of your process to do. The additional variables you are declaring are independent semaphores from those in the array. Assignment will only copy the sem_t
value (which is going to technically cause undefined behavior because you didn't initialize them).
You can just pass a pointer to the sem_t
in the array to sem_init
:
sem_init(&sems[0], 0, 1);
sem_init(&sems[1], 0, 0);
sem_init(&sems[2], 0, 0);
If you can use C 20, consider using the C standard library's semaphore types instead. They have a proper C API instead of the C API you are using here. See https://en.cppreference.com/w/cpp/header/semaphore.
Also, given that you have tagged pthreads, don't use pthreads directly if you are using C 11 or later (which you should) and use the standard library threading facilities instead, see https://en.cppreference.com/w/cpp/thread/thread.