2013-10-23 21 views
-4

我試圖爲函數*生產者創建一個線程,但創建線程的行顯示錯誤。我出演線,但我有麻煩搞清楚什麼是錯的...創建Pthreads

#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); 
} 
+0

並且錯誤是? – Cramer

+0

** pthread_create(&pro,NULL,producer,&buf); **這不是編譯,我不知道爲什麼,因爲我相信多數民衆贊成你如何調用函數.. –

+0

當它停止編譯,它說什麼? – Cramer

回答

0

我沒有看到你呼籲pthread_mutex_t mutpthread_cond_t notFull的初始化在你的結構的任何地方。

此外,你需要改變你的函數聲明的順序,或添加原型到文件的頂部。

1

您必須在pthread_create調用之前聲明生產者。

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

應該先出現。

同樣,必須首先聲明mClock。

此外,該函數應該只帶一個參數