test_cond.cpp

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>


bool tready = false;
int count = 0;

pthread_cond_t tcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t tlock = PTHREAD_MUTEX_INITIALIZER;

//#define TEST_MULTISENDER
#define TEST_MULTIWAITOR
//#define TEST_BROADCAST


void* ThreadSender(void* a)
{
    int idx = count++;
    printf("start sender %d!n", idx);
    pthread_mutex_lock(&tlock);
    printf("sender %d signaled!n", idx);
    //tready = true;
    #ifdef TEST_BROADCAST
        pthread_cond_broadcast(&tcond);
    #else
        pthread_cond_signal(&tcond);
    #endif
    pthread_mutex_unlock(&tlock);
    printf("sender %d exit...n", idx);
}

void* ThreadWaitor(void* a)
{
    printf("start waitor!n");
    pthread_mutex_lock(&tlock);
    //while(!tready) 
        pthread_cond_wait(&tcond, &tlock);
    printf("get signal!n");
    pthread_mutex_unlock(&tlock);
    printf("waitor exit...!n");
}


void* ThreadWaitor2(void* a)
{
    printf("start waitor 2!n");
    pthread_mutex_lock(&tlock);
    //while(!tready) 
        pthread_cond_wait(&tcond, &tlock);
    printf("waitor 2 get signal!n");
    pthread_mutex_unlock(&tlock);
    printf("waitor 2 exit...!n");
}


int main()
{
    printf(" >>>>>>>>>>>>>test start<<<<<<<<<<<<<<n");
    pthread_t tid1, tid2, tid3;

    #if defined(TEST_MULTISENDER)
    pthread_create(&tid1, NULL, ThreadSender, NULL);
    #elif defined(TEST_MULTIWAITOR)
    pthread_create(&tid3, NULL, ThreadWaitor2, NULL);
    #endif
    sleep(1);
    pthread_create(&tid2, NULL, ThreadWaitor, NULL);
    sleep(1);
    pthread_create(&tid1, NULL, ThreadSender, NULL);


    sleep(1);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);

    printf(" >>>>>>>>>>>>>test over<<<<<<<<<<<<<<n");
    return 0;
}