创建Pthreads

时间:2013-10-23 23:28:05

标签: c multithreading pthreads

我正在尝试为函数* producer创建一个线程,但创建线程的行显示错误。我主演了这一行,但我无法弄清楚它有什么问题......

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>

#define TOTALLOOPS 100                              /*Num of loops run*/
#define NUMOFPAIRS 4 /*For each 1 it produces 1 consumer and 1 producer*/

typedef struct {
    int q[NUMOFPAIRS];
    int head;
    int tail;
    int full;
    int empty;
    pthread_mutex_t mut;                       /*Creates a mutex Lock*/
    pthread_cond_t notFull;                     /*Creates conditional*/
}Queue;

int main(void)
{
    Queue buf;              /* Declare and initialize parts of struct */
    buf.head = 0;
    buf.tail = 0;
    buf.full = 0;
    buf.empty = 0;
    pthread_mutex_init(&buf.mut, NULL);/*intitializes mutex for struct*/
    //pthread_cond_init(&buf.nutFull, NULL);

    pthread_t pro;
    **pthread_create(&pro, NULL, producer, &buf);**


    pthread_mutex_destroy(&buf.mut);
    return 0;
}

void *producer(int x, Queue *buf){
    int id = x;
    int i;

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

        while(buf->full == 1){
            //do nothing
        }
        mClock();
        printf(" - Producer%d:\n",  id);
    }
}

void* consumer(int x, Queue *buf){
    int id = x;
    int i;

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

        while(buf->empty == 1){
            //do nothing
        }
        mClock();
        printf(" - Consumer%d:\n",  id);
    }
}

void addToQueue(Queue *buf, int x){
    //Checks if empty flag is triggered, if so un triggers
    if(buf->empty) buf->empty = 0;

    buf->q[buf->tail] = x;
    if(buf->tail == 3) buf->tail = 0;  /*Resets to beginning if at end*/
    else buf->tail += 1;                     /*else just moves to next*/

    //Checks if full flag needs to be triggered, if so triggers
    if(buf->tail == buf->head) buf->full = 1;
}

int removeFromQueue(Queue *buf){
    int t;                                   /*return value from queue*/

    //Checks if full flag is triggered, if so un triggers
    if(buf->full == 1)buf->full = 0;

    t = buf->q[buf->head];
    if(buf->head == 3) buf->head = 0;  /*Resets to beginning if at end*/
    else buf->head += 1;                     /*else just moves to next*/

    //Checks if full flag needs to be triggered, if so triggers
    if(buf->tail == buf->head) buf->empty = 1;

    return t;
}

void mClock(){
    struct timeval tv;
    gettimeofday(&tv,NULL);
    long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
    printf("%u", time_in_micros);
}

2 个答案:

答案 0 :(得分:1)

你必须在pthread_create调用之前声明producer。

void *producer(int x, Queue *buf);

应该先出现。

同样,必须首先声明mClock。

此外,该函数应该只接受一个参数

答案 1 :(得分:0)

我看不到您在任何地方为pthread_mutex_t mutpthread_cond_t notFull调用初始值设定项。

此外,您需要更改函数声明的顺序,或将原型添加到文件的顶部。