C信号量线程读取文件

发布于 2024-12-09 07:30:16 字数 641 浏览 1 评论 0原文

我编写代码,其中有三个线程从文件中读取行,还有三个线程写入文件。当读取这些行时,它们被存储在缓冲区内。读取完成后将被激活。我已经尝试过这一点,并且能够使其仅与一个用于读取的线程和一个用于写入的线程一起工作。此刻我很失落。 任何帮助都会很棒。

这是我编写的代码片段。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

行雁书 2024-12-16 07:30:16

首先,这里有很多事情不清楚,例如各种参数和标志的定义。

从我从你的两个函数中可以看出,你有多个生产者/消费者问题。对于多个消费者(即读者)来说,拥有信号量是有意义的。但是在写入时,使用互斥锁来序列化生产者线程更有意义。

如果让多个生产者线程写入同一个文件,文件就会出现乱码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文