我正在学习使用信号量对象。但我无法初始化它。sem_init 函数总是返回值 -1 风雨无阻。
返回值 -1 表示第一个参数不是有效的指针,比如我的参考。但我在我的代码中找不到错过打印。我在 OS X 上的 Xcode 中编译了我的代码。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
void * thread_snd(void *arg);
void * thread_rcv(void* arg);
sem_t bin_sem;
int number = 0;
char thread1[] = "A thread";
char thread2[] = "B thread";
char thread3[] = "C thread";
int main(int argc, char** argv)
{
pthread_t t1, t2 ,t3;
void *thread_result;
int state;
state = sem_init(&bin_sem, 0, 0);
if(state != 0)
{
puts("fail to initialize semaphore");
exit(1);
}
pthread_create(&t1, NULL, thread_snd, &thread1);
pthread_create(&t2, NULL, thread_rcv, &thread2);
pthread_create(&t3, NULL, thread_rcv, &thread3);
pthread_join(t1, &thread_result);
pthread_join(t2, &thread_result);
pthread_join(t3, &thread_result);
printf("final number : %d \n", number);
sem_destroy(&bin_sem);
return 0;
}
void * thread_snd(void * arg)
{
int i;
for(i = 0 ; i < 4; i++)
{
while(number != 0)
sleep(1);
number++;
printf("execution : %s, number : %d \n", (char*) arg, number);
sem_post(&bin_sem);
}
}
void * thread_rcv(void* arg)
{
int i;
for(i = 0 ; i < 2; i++)
{
sem_wait(&bin_sem);
number--;
printf("execution : %s number : %d \n", (char*)arg, number);
}
}