【发布时间】:2020-09-22 15:27:58
【问题描述】:
我正在使用锁和条件变量编写生产者消费者问题。这是一个简单的程序,我在缓冲区中使用 int。生产者完成生产后如何阻止消费者等待?
void do_fill(int i){
buffer[fill_ptr].chunkNumber = i;
buffer[fill_ptr].size = 1024;
buffer[fill_ptr].startPointer = dst + (i * 1024);
fill_ptr = (fill_ptr+1) % max;
numfull++;
}
int do_get(){
int temp_chunk = buffer[use_ptr].chunkNumber;
char *temp_start = buffer[use_ptr].startPointer;
int temp_size = buffer[use_ptr].size;
use_ptr = (use_ptr+1) %max;
printf("%d %c %d \n", temp_chunk,*temp_start,temp_size);
numfull--;
return temp_chunk;
}
void *producer(void *arg)
{
for (int cant = 0; cant < 5; ++cant)
{
printf("IN PRODUCER\n");
pthread_mutex_lock(&m); // p1
while (numfull == max) // p2
pthread_cond_wait(&empty, &m); // p3
do_fill(cant); // p4
pthread_cond_signal(&fill); // p5
pthread_mutex_unlock(&m);
}
}
void *consumer(void *arg)
{
for (int i=0;i<5;i++)
{
printf("IN CONS\n");
pthread_mutex_lock(&m);
// c1
while (numfull == 0)
{
// c2
pthread_cond_wait(&fill, &m);
} // c3
int temp = do_get();
pthread_cond_signal(&empty); // c5
pthread_mutex_unlock(&m); // c6
}
}
【问题讨论】:
-
请edit您的问题并将您的代码复制并粘贴为文本而不是显示屏幕截图。见meta.stackoverflow.com/questions/285551/… 没有看到缺失的功能就很难给出建议。也许有一种方法可以检测“没有更多数据”/EOF 条件。
标签: c multithreading