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

pthread_cond_t  condA  = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ProcessRow = 0 ;

#define LOOPCNT 100

void *producer()
{
    int idx ;
    for(idx=0;idx<LOOPCNT;idx++)
    {
        /*
        __sync_add_and_fetch(&ProcessRow,1) ;
        pthread_cond_signal(&condA);
        printf("sending signal...(%d)\n",ProcessRow) ;
        */
        ProcessRow = 1 ;
        pthread_cond_signal(&condA);
        printf("sending signal...(%d)\n",ProcessRow) ;
    }
    printf("I am out ... \n") ;
}

void *consumer()
{
    int icnt = 0 ;
    while(1)
    {
        /*
        pthread_mutex_lock(&mutex);
        while (ProcessRow <= 0)
            pthread_cond_wait(&condA, &mutex);
        pthread_mutex_unlock(&mutex);

        __sync_sub_and_fetch(&ProcessRow,1) ;
        printf("receving=(%d)\n",ProcessRow) ;
        ++icnt ;
        */
        pthread_mutex_lock(&mutex);
        while (ProcessRow <= 0)
            pthread_cond_wait(&condA, &mutex);
        pthread_mutex_unlock(&mutex);

        ProcessRow = 0 ;
        ++icnt ;
        printf("icnt=(%d)\n",icnt) ;
    }
    printf("(%d)\n",ProcessRow) ;
}

int main()
{

    printf("sem1 and sem2 fine \n") ;
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,producer,NULL);
    pthread_create(&tid2,NULL,consumer,NULL);
    sleep(1) ;
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

 }

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

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