C信号量线程读取文件
我编写代码,其中有三个线程从文件中读取行,还有三个线程写入文件。当读取这些行时,它们被存储在缓冲区内。读取完成后将被激活。我已经尝试过这一点,并且能够使其仅与一个用于读取的线程和一个用于写入的线程一起工作。此刻我很失落。 任何帮助都会很棒。
这是我编写的代码片段。
void *read_file(void *arg)
{
semaphore_down(&sem_write);
while(fgets(temp, MAX_BUFFER, file) != NULL)
{
if(!isFull(&b))
{
printf("ADDING\n");
read(&b,temp);
}
}
semaphore_up(&sem_read);
}
void *write_file(void *arg)
{
semaphore_down(&sem_read);
while(!isEmpty(&b))
{
write(&b,&temp2);
fprintf(file2, "%s", temp2);
}
semaphore_up(&sem_write);
}
任何帮助将非常感激
I writing code where i have three threads that read lines from a file, and 3 three threads what write to the file. When the lines are read they are stored inside a buffer. when reading is completed would be activated. I have had a go at this and i'm able to make it work only with one thread for reading and one for thread for writing. At the moment i am pretty lost.
Any help would be great.
Here are the fragments of code which i have written.
void *read_file(void *arg)
{
semaphore_down(&sem_write);
while(fgets(temp, MAX_BUFFER, file) != NULL)
{
if(!isFull(&b))
{
printf("ADDING\n");
read(&b,temp);
}
}
semaphore_up(&sem_read);
}
void *write_file(void *arg)
{
semaphore_down(&sem_read);
while(!isEmpty(&b))
{
write(&b,&temp2);
fprintf(file2, "%s", temp2);
}
semaphore_up(&sem_write);
}
Any help would be very much appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这里有很多事情不清楚,例如各种参数和标志的定义。
从我从你的两个函数中可以看出,你有多个生产者/消费者问题。对于多个消费者(即读者)来说,拥有信号量是有意义的。但是在写入时,使用互斥锁来序列化生产者线程更有意义。
如果让多个生产者线程写入同一个文件,文件就会出现乱码。
First of all many things are not clear here such as definitions of various parameters, and flags.
From what I can udnerstand from your 2 functions, You have multiple Producers/Consumers problem. For multiple consumers i.e. readers it makes sense to have a semaphore. But while writting, it makes more sense to have a mutex for serializing the producers threads.
If you let multiple producer threads write into the same file, the file will be garbled.