我正在學習Pthread編程。這是我在作業結束時得到的問題:
我想通過使用producer-consumer
問題將源文件中的每個字節複製到新的.txt
文件中。
這裏是我的代碼結構:生產者 - 消費者模型的最終條件
void *producer(....) {
while(1){
nsleep();
read_byte(....);
nsleep();
produceToBuffer(....);
}
}
void *consumer(....) {
while(1){
nsleep();
consumeFromBuffer(....);
nsleep();
write_byte(....);
}
}
int main() {
pthread_t inThread[nIn];
pthread_t outThread[nOut];
//initialize mutex locks for all functions
pthread_mutex_init(&_mutexConsume, NULL);
pthread_mutex_init(&_mutexProduce, NULL);
pthread_mutex_init(&_mutexWrite, NULL);
pthread_mutex_init(&_mutexRead, NULL);
sem_init(&empty, 0, size); //initialize semaphore signal the empty slots available
sem_init(&full, 0, 0); //initialize semaphore full signal
for(i = 0; i < nIn; i++) {
pthread_create(inThread+i, NULL, producer, null);
}
for(j = 0; j < nOut; j++) {
pthread_create(outThread+i, NULL, consumer, null);
}
}
我的問題是:在文件的結尾,這是pthread_exit(0);
當EOF檢測,但對於消費者線程,我的想法是生產者線程完成要麼在睡眠後完成,要麼在所有消費者線程都在等待信號量滿時結束。
有人可以幫助我嗎?
我不知道我理解你的題。你所展示的不可編譯的半僞代碼會讓情況變得更糟。你不知道如何告訴消費者輸入結束了?一種可能的方法是通過在緩衝隊列中插入一個特殊值來指示這一點。 –