首页 > 代码库 > 一个线程和信号量的例子

一个线程和信号量的例子

///编译时加上-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\n"); sem_wait(&sem1);printf(" 1\n");sem_post(&sem2); sem_wait(&sem1);printf(" 3\n");sem_post(&sem2); sem_wait(&sem1);printf(" 5\n");sem_post(&sem2); sem_wait(&sem1);printf(" 7\n");sem_post(&sem2); sem_wait(&sem1);printf(" 9\n");sem_post(&sem2); sem_wait(&sem1);printf(" 11\n");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!\n");  exit(EXIT_FAILURE); } sleep(1); sem_post(&sem1);sem_wait(&sem2);printf("2\n"); sem_post(&sem1);sem_wait(&sem2);printf("4\n"); sem_post(&sem1);sem_wait(&sem2);printf("6\n"); sem_post(&sem1);sem_wait(&sem2);printf("8\n"); sem_post(&sem1);sem_wait(&sem2);printf("10\n"); sem_post(&sem1);sem_wait(&sem2);printf("12\n"); pthread_join(thread,NULL); return 0;}

 

一个线程和信号量的例子