我正在尝试使用pthread解决生产者/消费者问题,而且我有点坚持实施。
多个生产者打开文件并逐行读取,并将这些行放在固定缓冲区中。如果缓冲区已满,则每个生成器等待并通知消费者从缓冲区读取并写入文件..这样做直到从文件中读取每一行。
char *buffer[20]; //shared buffer
void* Producer(void* args){
struct Data *data = (struct Data*) args;
FILE* fp;
char buf[file_buffer];
if ((fp = fopen(data->file_name, "r")) == NULL)
{ /* Open source file. */
perror("Couldn't open file.");
exit(0);
}
pthread_mutex_lock(&the_mutex); /* protect buffer */
while (isFUll()) /* If the buffer is full wait */
pthread_cond_wait(&condp, &the_mutex);
//read and add to buffer
while (fgets(buf, sizeof(buf), fp) != NULL)
{
buf[strlen(buf) - 1] = '\0'; // each line from file
//add line to buffer here
}
pthread_cond_signal(&condc); /* wake up consumer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
fclose(fp);
return 0;
}
如果缓冲区已满但是文件中的读数未完成,那么生产者是否会继续从中断处继续读取?如果n