一个线程和信号量的例子

///编译时加上-lpthread

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <pthread.h>

#include <semaphore.h>
sem_t sem1,sem2;

void fun(void *arg)
{
 printf("fall asleep
");
 sem_wait(&sem1);printf(" 1
");sem_post(&sem2);
 sem_wait(&sem1);printf(" 3
");sem_post(&sem2);
 sem_wait(&sem1);printf(" 5
");sem_post(&sem2);
 sem_wait(&sem1);printf(" 7
");sem_post(&sem2);
 sem_wait(&sem1);printf(" 9
");sem_post(&sem2);
 sem_wait(&sem1);printf(" 11
");sem_post(&sem2);
 exit(EXIT_FAILURE);
}

int main()
{
 pthread_t thread;
 int arg=1,res;
 sem_init(&sem1,0,0);
 sem_init(&sem2,0,0);
 res=pthread_create(&thread,PTHREAD_CREATE_JOINABLE,(void*)fun,NULL);
 if(res)
 {
  printf("pthread_create error!
");
  exit(EXIT_FAILURE);
 }
 sleep(1);
 sem_post(&sem1);sem_wait(&sem2);printf("2
");
 sem_post(&sem1);sem_wait(&sem2);printf("4
");
 sem_post(&sem1);sem_wait(&sem2);printf("6
");
 sem_post(&sem1);sem_wait(&sem2);printf("8
");
 sem_post(&sem1);sem_wait(&sem2);printf("10
");
 sem_post(&sem1);sem_wait(&sem2);printf("12
");
 pthread_join(thread,NULL);
 return 0;
}
原文地址:https://www.cnblogs.com/CoderTian/p/4200780.html