我不得不用我没有经验的Posix Pthreads解决读者-作家问题中的同步问题。
该任务包括产生3个阅读器和1个编写器,编写器将队列填充以供阅读器打印。我在同步访问队列时遇到麻烦。队列包含我已测试并显示为有效的方法。
如果队列已满,则应向读取器发出信号以读取/清空队列。然后,一旦其为空,编写器应再次开始使用随机值填充队列。仅适用于total_tasks
。
我大多不确定锁定/解锁和信号的正确位置。
当前执行时,得到以下输出。似乎在完成任何操作之前已经完成了线程处理?
先谢谢了。
Reader Thread 0 Created
Reader Thread 1 Created
Reader Thread 2 Created
Writer Thread Created
Reader Thread 0 Finished
Reader Thread 1 Finished
Reader Thread 2 Finished
Writer Thread Finished
<<STUCK FOREVER>>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define TRUE 1
#define FALSE 0
int total_tasks = 0;
int fin = FALSE;
pthread_cond_t qEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t qFull = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* writer();
void* reader();
#include "rw.h"
#include "queue.h"
queue* q;
int main()
{
int i, j;
total_tasks = 15;
q = newQueue(5);
pthread_t readerTID[3];
pthread_t writerID;
//Create 1 Writer Thread
printf("Writer Thread Created\n");
pthread_create(&writerID, NULL, writer, NULL);
printf("Writer Thread Finished\n");
pthread_join(writerID, NULL);
return 0;
}
void* writer()
{
int num1 = 0;
int num2;
int fin = FALSE;
time_t t;
srand((unsigned) time(&t));
while(!fin)
{
printf("w1");
pthread_mutex_lock(&mutex);
while(isFull(q))//While the queue is full
{
pthread_cond_wait(&qEmpty, &mutex); //Wait for the readers to empty the queue
}
if(num1 < total_tasks)//if we havent done all the tasks
{
while(!(isFull)) //If the queue isnt full - Fill with values
{
printf("w2");
num2 = (rand() % 20);
enqueue(q, num1, num2);
num1++;
}
pthread_cond_signal(&qFull); //Signal queue is full
}
else
{
fin = TRUE;
}
pthread_mutex_unlock(&mutex);
}
}