2016-04-19 136 views
0

我已經實施了一個解決方案,使用pthreads和信號量在C中的生產者/消費者問題。緩慢的pthread消費者

我的主線程是生產者,我啓動N個消費者線程。

我的代碼是:

typedef struct 
{ 
    int buf[BUFSIZE];  /* shared var */ 
    int in;    /* buf[in%BUFSIZE] is the first empty slot */ 
    int out;    /* buf[out%BUFSIZE] is the first full slot */ 
    sem_t full;   /* keep track of the number of full spots */ 
    sem_t empty;   /* keep track of the number of empty spots */ 
    pthread_mutex_t mutex;   /* enforce mutual exclusion to shared data */ 
} CONSUMER_STRUCT; 

CONSUMER_STRUCT shared; 

這是我的每一個消費者線程的代碼:

void *Consumer(void *arg) 
{ 
    int fd, workerID, i, hit=0; 

    workerID = *(int *)arg; 

    for (;;) { 
     sem_wait(&shared.full); 
     pthread_mutex_lock(&shared.mutex); 
     fd = shared.buf[shared.out]; 
     printf("\n[C%d] Consumed. I got %d ...Valor do buffer: %d na posição %d\n\n\n", workerID, fd, shared.buf[shared.out], shared.out); 
     ftp(fd, hit); 
     shared.buf[shared.out] = 0; 
     shared.out = (shared.out+1)%BUFSIZE; 
     fflush(stdout); 
     printf("\n\n\n\nEstado do buffer:\n\n\n\n"); 
     for (i = 0; i < BUFSIZE; i++) { 
      //printf("%d ", shared.buf[i]); 
     } 
     /* Release the buffer */ 
     pthread_mutex_unlock(&shared.mutex); 
     /* Increment the number of full slots */ 
     sem_post(&shared.empty); 
     hit++; 
    } 
    return NULL; 
} 

這是我的生產者線程代碼:

item = socketfd; 

sem_wait(&shared.empty); 
pthread_mutex_lock(&shared.mutex); 

shared.buf[shared.in] = item; 

shared.in = (shared.in + 1) % BUFSIZE; 
fflush(stdout); 

pthread_mutex_unlock(&shared.mutex); 
sem_post(&shared.full); 

一切工作正常,但服務22個文件需要大約20秒,而每個請求創建一個線程大約需要2個秒!這似乎是一次執行一個線程,我想要「同時」執行所有的線程。

我在執行方法中做錯了什麼?

+1

您的消費者在整個操作過程中都持有互斥鎖。您正在運行單線程同步開銷。 – EOF

+0

我明白你的意思了!什麼應該是解決這個問題的正確方法? – rafaelcpalmeida

+2

讓我們暫時假設Consumer()中的'ftp()'支配着消費者的執行時間。此外,我們假設'ftp()'是線程安全的。然後,你可以在'pthread_mutex_unlock()'下面移動'ftp()'並且實際同時執行。 – EOF

回答

0

對於那些可能來到這裏有類似問題的人,這裏是修復。

感謝@Martin James和@EOF。

void *Consumer(void *arg) 
{ 
    int fd, workerID, i, hit=0; 

    workerID = *(int *)arg; 

    for (;;) { 
     sem_wait(&shared.full); 
     pthread_mutex_lock(&shared.mutex); 
     fd = shared.buf[shared.out]; 
     shared.buf[shared.out] = 0; 
     shared.out = (shared.out+1)%BUFSIZE; 
     pthread_mutex_unlock(&shared.mutex); 
     printf("\n[C%d] Consumed. I got %d ...Valor do buffer: %d na posição %d\n\n\n", workerID, fd, shared.buf[shared.out], shared.out); 
     ftp(fd, hit); 
     fflush(stdout); 
     printf("\n\n\n\nEstado do buffer:\n\n\n\n"); 
     for (i = 0; i < BUFSIZE; i++) { 
      //printf("%d ", shared.buf[i]); 
     } 
     /* Release the buffer */ 
     /* Increment the number of full slots */ 
     sem_post(&shared.empty); 
     hit++; 
    } 
    return NULL; 
} 

問題是我鎖定互斥鎖,執行一個函數,然後解鎖互斥鎖。這是執行過程中造成如此多延遲的原因。

相關問題