简体   繁体   中英

Using a dedicated thread for file output

I have a multi threaded program that simulates a theme park, and writes log messages to a given text file. I originally tried to have every thread write to the file, but I was running into errors with the threads accessing the file pointer.

Instead it was suggested I use a dedicated thread for writing, and write to a buffer in all other methods that this specific thread will then write to the file. Obviously I need a mutex to synchronize access to the buffer, but is there a way to signal the writing thread first after every buffer write so that it has a chance to write the buffer to the file before the mutex is signaled to every method trying to write to the buffer?

I solved my problem by using 2 mutexs. the first is locked at the beginning of execution. The second is locked when a write to the buffer occurs. once the write is finished, the first mutex is unlocked, which allows the thread to write to output. once it writes to output it unlocks the second mutex so something else can be written to buffer.

the output thread:

void *output_logging(void *path)
{
    while(END)
    {
        FILE *write = fopen(path, "w+");
        while(1)
        {
            pthread_mutex_lock(&tlock);
            fputs(BUFFER, write);
            pthread_mutex_unlock(&write_lock);
        }
    }
}

and an example of a write:

pthread_mutex_lock(&write_lock);
sprintf(BUFFER, "Beginning of Simulation\n");
pthread_mutex_unlock(&tlock);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM