views:

379

answers:

3

I have implemented multithreaded shared library in C++ (For Linux and Windows). I would like to add logging mechanism inside the library itself. The caller of the library is not aware of that. The log file would be same so i am wondering how could i design the thread safe logging if multiple process is using my library and trying to open and log into the same log file.

Thanks in Advnace.

+1  A: 

Your library shares the log file with the client application? If so, there is absolutely no way to do thread-safe logging. The client could just create a thread and log while calling you.

Otherwise, you have two options:

  1. Use a mutex. Simplest solution.
  2. Have a logging thread with a lock-free (you'll probably be able to get away with a mutex) FIFO queue of messages that is created/destroyed when your library is created/destroyed. I hope you have an init/deinit function...

The difference b/w 1 and 2 is that for 1, you hold a mutex for the full I/O operation. In the second, you only hold a mutex for as long as it takes to push a message at the back of the queue, which can be a constant operation if you do it right.

cheez
Thanks. i know about mutex but thought that it would be slow if multiple process are using the library. Second option is good but again the library is not supposed to create any new thread, its a restriction. But thanks a lot for the idea.
Adil
+2  A: 

You can try using log4cpp library.

Alexander Vakrilov
+1  A: 

Use file locking. I believe fcntl is POSIX compliant so should work on Windows too. Does your code use Posix calls?

With fcntl, you should be able to lock a specific range of bytes. So if you seek to end and try to lock out the amount of bytes you are about to write, it should be pretty fast. To obtain the lock, you can probably spin, relinquishing the CPU for a small amount of time, if you don't obtain the lock.

Moron
Yes i am using POSIX calls. Thanks.
Adil
Learn something new everyday :)
cheez