如何使用pthread条件等待

时间:2014-04-18 00:49:20

标签: c multithreading pthreads posix

我想学习如何使用pthread条件等待和pthread广播在有可用于处理的数据时唤醒所有消费者线程。我试图学习如何让消费者线程等到生产者线程读取了一些数据量,并且当有数据可用时向所有消费者线程发送信号以消耗数据然后再等待生产者在一个周期中再次开展工作。

/*
 * thread.c
 *
 *  Created on: Apr 17, 2014
 *      Author: dev-1
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <ctype.h>
#include <pthread.h>

typedef struct tempS_ tempS;
struct tempS_ {

    char name[10];
    int temp;
};

pthread_mutex_t cd_lock;

void *processorThread(void *arg) {

    tempS* tempN = (tempS*) arg;
    int temp = tempN->temp;
    int i;

    pthread_mutex_lock(&cd_lock);

    for (i = 0; i < 10; i++) {

        printf("temp: %d %s\n", temp + 1, tempN->name);
    }

    pthread_mutex_unlock(&cd_lock);

    return 0;
}

int main(int argc, char *argv[]) {

    int threads = 3;
    int i;

    pthread_t * thread = malloc(sizeof(pthread_t) * threads);
    int ret = 0;

    pthread_mutex_init(&cd_lock, NULL);

    for (i = 0; i < threads; i++) {

        tempS* temp = malloc(sizeof(tempS));
        strcpy(temp->name, "hello");
        temp->temp = 2;

        ret = pthread_create(&thread[i], NULL, processorThread, temp);

        if (ret != 0) {

            printf("Create pthread error!\n");
            exit(1);
        }
    }

    for (i = 0; i < threads; i++) {

        pthread_join(thread[i], NULL);
    }

    return 0;
}

0 个答案:

没有答案