-4

我正在尝试为函数 *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);
}
4

2 回答 2

1

您必须在 pthread_create 调用之前声明生产者。

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

应该首先出现。

同样,必须首先声明 mClock。

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

于 2013-10-23T23:31:34.803 回答
0

我看不到您在哪里调用初始化程序pthread_mutex_t mut以及pthread_cond_t notFull在任何地方的结构中。

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

于 2013-10-23T23:31:24.147 回答