Ok, I'm now using sem_open instead, and I have added a global variable "i" that one thread increments and the other decrements. I still have the same problem, the thread with the sem_wait call should go to sleep if the semaphore reaches zero so no negative values of "i" should be possible if this worked.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_t new_thread;
sem_t *sem = NULL;
int i = 0;
void *thread_print(){
while(1){
sem_wait(sem);
i--;
printf("1: %d\n", i);
}
}
void print_main(){
while(1){
i++;
printf("2: %d\n", i);
sem_post(sem);
}
}
int main()
{
sem = sem_open("semaphore", O_CREAT, 0, 0);
if(!sem)
exit(1);
int err = pthread_create( &new_thread, NULL, thread_print, NULL);
if(err)
exit(1);
print_main();
sem_close(sem);
return 0;
}
The thing I'm a bit unsure about is the third argument in sem_open it's for setting permissions, it can be left out so I just set it to zero, the last parameter is the initial value of the semaphore.