码迷,mamicode.com
首页 > 编程语言 > 详细

一个线程和信号量的例子

时间:2015-01-04 13:31:29      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

///编译时加上-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;
}

 

一个线程和信号量的例子

标签:

原文地址:http://www.cnblogs.com/CoderTian/p/4200780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!