首页 > 代码库 > 一个线程和信号量的例子
一个线程和信号量的例子
///编译时加上-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;}
一个线程和信号量的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。