无名信号量

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

sem_t sem1,sem2;

void *thread1()
{
	int i=10;
	while(i)
	{
		sem_wait(&sem1);
		printf("hello,boy.\n");
		sem_post(&sem2);
		i--;
		//sleep(1);
	}
}

void *thread2()
{
	int i=10;
	while(i)
	{
		sem_wait(&sem2);
		printf("hello,boy....................\n");
		sem_post(&sem1);
		i--;
	    //sleep(1);
	}
}

int main()
{
	int ret;
	pthread_t pth1,pth2;
	time_t begin,end;
	struct tm beg_time;
	struct tm end_time;
	//struct tm *tp = &timee;
	//long int first,over;

	time( &begin );
	localtime_r( &begin, &beg_time );
	printf("time is:%s", asctime(&beg_time));
	ret = sem_init(&sem1, 0, 1);
	if( 0 != ret )
	{
		perror("sem_init error");
		return -1;
	}
	
	ret = sem_init(&sem2, 0, 0);
	if( 0 != ret )
	{
		perror("sem_init error");
		return -1;
	}

	ret = pthread_create(&pth1, NULL, thread1, NULL);
	if( 0 != ret )
	{
		perror("pthread_create pth1 error");
		return -1;
	}
	ret = pthread_create(&pth2, NULL, thread2, NULL);
	if( 0 != ret )
	{
		perror("pthread_create pth2 error");
		return -1;
	}
	
	pthread_join( pth1, NULL);
	printf("thread1 is over !!! \n ");
	pthread_join( pth2, NULL);
	printf("thread2 is over !!! \n ");
    
	sem_destroy(&sem1);
	sem_destroy(&sem2);

	time(&end);
	localtime_r( &end,&end_time );
	
	printf("time is:%s", asctime(&end_time));
	//printf("time is:%s", asctime( localtime(&end) ));
	printf("%ld - %ld===%ld\n", end, begin, end - begin);
	end += 180;
	localtime_r( &end,&end_time );
	//localtime_r( &end,&end_time );
	//printf("time is:%s", asctime( localtime(&end) ));
	printf("+180 ,time is:%s", asctime(&end_time));
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值