Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing (logging) into same file from different threads , different functions?

In C++ is there any way to make the writing into file thread safe in the following scenario ?

void foo_one(){
lock(mutex1);
//open file abc.txt
//write into file
//close file
unlock(mutex1);
}

void foo_two(){
lock(mutex2);
//open file abc.txt
//write into file
//close file
unlock(mutex2);
}

In my application (multi-threaded) , it is likely that foo_one() and foo_two() are executed by two different threads at the same time . Is there any way to make the above thread safe ?

I have considered using the file-lock ( fcntl and/or lockf ) but not sure how to use them because fopen() has been used in the application ( performance reasons ) , and it was stated somewhere that those file locks should not be used with fopen ( because it is buffered )

PS : The functions foo_one() and foo_two() are in two different classes , and there is no way to have a shared data between them :( , and sadly the design is such that one function cannot call other function .

like image 837
k0n3ru Avatar asked Oct 15 '12 05:10

k0n3ru


People also ask

Can multiple threads write to the same file?

Multiple threads read the same file at the same time. In this case, there is no conflict. If multiple threads write the same file at the same time, write data will be lost.

Can multiple threads write to the same file Python?

Writing to the same file from multiple threads concurrently is not thread safe and may result in a race condition. Thread-safe means that writing or appending to the same file from more than one thread may result in a race condition.

What will happen if multiple threads accessing the same resource?

Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.

Can multiple threads read the same data?

Assuming there are no more writes and all previous writes are visible to the current thread, then yes reading the value from multiple threads is safe.


1 Answers

Add a function for logging.
Both functions call the logging function (which does the appropriate locking).

mutex  logMutex;
void log(std::string const& msg)
{
    RAIILock  lock(logMutex);

    // open("abc.txt");
    // write msg
    // close
}
like image 165
Martin York Avatar answered Oct 08 '22 15:10

Martin York