#include<stdio.h>
#include<pthread.h>
#include<fcntl.h>
#include<semaphore.h>

sem_t *sem1 ;
sem_t *sem2 ;

#define LOOPCNT 1000

void *producer()
{
    int idx ;
    sem_wait(sem1);
    for(idx=0;idx<LOOPCNT;idx++)
    {
        sem_post(sem2);
    }
    printf("I am out ... \n") ;
}

void *consumer()
{
    int icnt = 0 ;
    while(1)
    {
        sem_wait(sem2);
        ++icnt ;
        if(icnt >= LOOPCNT)
            break ;
        usleep(10000) ;
    }
    printf("(%d)\n",icnt) ;
}

int main()
{
    printf("sem1 and sem2 fine \n") ;
    sem1 = sem_open("semtest1",O_CREAT,0644,0);
    sem2 = sem_open("semtest2",O_CREAT,0644,0);
    printf("sem1 and sem2 fine \n") ;
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,producer,NULL);
    pthread_create(&tid2,NULL,consumer,NULL);
    sleep(1) ;
    sem_post(sem1) ;
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
}

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()