开发者

C Semaphore Thread read file

开发者 https://www.devze.com 2023-04-12 03:22 出处:网络
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 开发者_Python百

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 开发者_Python百科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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消