Posix pthread 多线程再学习

/*
 * =====================================================================================
 *
 *       Filename:  pthread_cond_test.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  04/07/2014 04:17:19 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Alan Wang (), [email protected]
 *   Organization:  
 *
 * =====================================================================================
 */
#include 
#include 
#include 
#include 
#include 
#include 

int flag = 1;

pthread_t tid1, tid2;
pthread_cond_t cond;
pthread_mutex_t mutex;

void *ret;

void *tid1_func(void *args) {

    int err = 0;

    struct timeval timeNow;
    struct timespec timedOut; 

    pthread_mutex_lock(&mutex);

    while(flag) {
        
        gettimeofday(&timeNow, NULL);
        timedOut.tv_sec = timeNow.tv_sec + 2;
        timedOut.tv_nsec = timeNow.tv_usec * 1000;

        err = pthread_cond_timedwait(&cond, &mutex, &timedOut);
        if (err != 0) printf("pthread_cond_timedwait failed and err = %d \n", -err);

    }

    pthread_mutex_unlock(&mutex);

}

void *tid2_func(void *args) {

    flag = 0;

    pthread_mutex_lock(&mutex);
    pthread_cond_signal(&cond);
    pthread_mutex_lock(&mutex);

}

int main(void) {

    pthread_cond_init(&cond, NULL); 
    pthread_mutex_init(&mutex, NULL);

    while (0 != pthread_create(&tid1, NULL, tid1_func, NULL)) return 1;

    sleep(5);

    while (0 != pthread_create(&tid2, NULL, tid2_func, NULL)) return 1;

    pthread_join(tid1, ret);

   return 0;

}

你可能感兴趣的:(C/C++,Posix/Liunx)