2012-04-19 47 views
-8

我開始了與線程和我有一些問題解決的:Pthread的Ç同步化

這個程序會產生數的有序序列和第二個任務讀取它們並將它們打印在屏幕上。如何根據需要修復此問題?

預期輸出:

Consumed item: 1 
Consumed item: 2 
Consumed item: 3 
Consumed item: 4 
Consumed item: 5 
Consumed item: 6 

實際輸出:

Consumed item: 1 
Consumed item: 4 
Consumed item: 7 
Consumed item: 10 
Consumed item: 11 
Consumed item: 14 

程序:

#include <stdio.h> 
#include <pthread.h> 
#include <time.h> 

#define   NBUFFERS  2 

int item, in=0, out=0; 
int buffer[NBUFFERS]; 
int stop =0; 

void *ProducerTask(void *data) //This is the producer task 
{ 
    int nextp = 0; 
    struct timespec mytime; 
    mytime.tv_sec = 0; 
    mytime.tv_nsec = 200000000; 

    while (!stop) { 
      nanosleep(&mytime, NULL); 
      nextp++; 
      buffer[in] = nextp; /* produce a new item */ 
      in = (in + 1) % NBUFFERS; 
    } 
    pthread_exit(0); 
} 

void *ConsumerTask(void *data) 
{ 
    int nextc; 
    struct timespec mytime; 
    mytime.tv_sec = 0; 
    mytime.tv_nsec = 500000000; 

    while (!stop) { 
      nanosleep(&mytime, NULL); 
      nextc = buffer[out]; /* consume a item */ 
      out = (out + 1) % NBUFFERS; 
      printf("Consumed item: %d\n", nextc); 
    } 
    pthread_exit(0); 
} 

void *MonitorTask (void *data) //This is the monitor task 
{ 
    getchar(); 
    stop = 1; 
    pthread_exit(0); 
} 

void main(void) 
{ 
    pthread_t task1; 
    pthread_t task2; 
    pthread_t task3; 

    pthread_create (&task1, NULL, ProducerTask, NULL); 
    pthread_create (&task2, NULL, ConsumerTask, NULL); 
    pthread_create (&task3, NULL, MonitorTask, NULL); 

    pthread_join(task1,NULL); 
    pthread_join(task2,NULL); 
    pthread_join(task3,NULL); 

    printf("Main program exiting.\n"); 
} 
+3

「修復此程序」絕對不是描述問題的好方法。您需要正確指出並描述您的問題以獲得良好迴應 – 2012-04-19 06:40:31

+1

預期結果(或輸出)是什麼以及實際結果如何?換句話說,你的問題是什麼? – 2012-04-19 06:41:25

+0

當然!它改變了! – dani 2012-04-19 06:41:36

回答

3
int buffer[NBUFFERS]; 
int stop =0; 

是全球性的,並從多個線程訪問,他們沒有任何synchronization
下面的race condition一個問題,如果不問題。

內在聯繫的強化應該讓你至少在你做錯了什麼的頭痛。

+0

這可能也有幫助: [在不同c文件中訪問pthreads中的全局變量](http://stackoverflow.com/questions/7382636/accessing-global-variables-in-pthreads-in-different-c-files) – nacho4d 2012-04-19 06:45:36

2

共享資源至少需要鎖定和傳遞數據通常通過條件變量的線程通信來解決,參見this example(C++,但它顯示了我的觀點)。

編輯:在這種情況下,奇怪的輸出是由於你使用一個小的緩衝區和比生產者慢的消費者。