#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;
}
无名信号量
最新推荐文章于 2024-05-10 07:00:00 发布