I am trying to create a semaphore and practicing by using this simple program, though I am getting a bunch of deprecated warnings when compiling on macos. I have been looking and having trouble finding a solution to get the semaphore to work for macos.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#define THREAD_NUM 4
sem_t semaphore;
void* routine(void* args) {
sem_wait(&semaphore);
sleep(1);
printf("Hello from thread %d\n", *(int*)args);
sem_post(&semaphore);
free(args);
}
int main(int argc, char *argv[]) {
pthread_t th[THREAD_NUM];
sem_init(&semaphore, 0, 1);
int i;
for (i = 0; i < THREAD_NUM; i++) {
int* a = malloc(sizeof(int));
*a = i;
if (pthread_create(&th[i], NULL, &routine, a) != 0) {
perror("Failed to create thread");
}
}
for (i = 0; i < THREAD_NUM; i++) {
if (pthread_join(th[i], NULL) != 0) {
perror("Failed to join thread");
}
}
sem_destroy(&semaphore);
return 0;
}
I am expecting the threads to be created for the routine function where 4 threads exist for 4 void* routine(). It should printf("Hello from thread") every second starting from thread 0 and going to 3. What is actually happening is all the printf statements get outputed to the console after 1 second at the same time.
Output:
Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3
Compiler information:
test.c:18:1: warning: non-void function does not return a value [-Wreturn-type]
}
^
test.c:22:5: warning: 'sem_init' is deprecated [-Wdeprecated-declarations]
sem_init(&semaphore, 0, 4);
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/semaphore.h:55:42: note: 'sem_init' has been explicitly marked deprecated here
int sem_init(sem_t *, int, unsigned int) __deprecated;
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/cdefs.h:204:40: note: expanded from macro '__deprecated'
#define __deprecated __attribute__((__deprecated__))
^
test.c:37:5: warning: 'sem_destroy' is deprecated [-Wdeprecated-declarations]
sem_destroy(&semaphore);
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/semaphore.h:53:26: note: 'sem_destroy' has been explicitly marked deprecated here
int sem_destroy(sem_t *) __deprecated;
^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/cdefs.h:204:40: note: expanded from macro '__deprecated'
#define __deprecated __attribute__((__deprecated__))
^
3 warnings generated.