[font="Times New Roman"]"file.txt" becomes a mess when I run the code (thread 1 is sometimes shown twice, sometimes thread 2 is shown twice, sometimes its correct, sometimes only one is shown once). What am I doing wrong?[/font]
[font="Times New Roman"]I am on Ubuntu Linux
[/font]
[font="Times New Roman"]Thanks in advance,[/font]
[font="Times New Roman"]Gasim[/font]
I'm not a boost expert at all, but you create a local mutex in each function and afterward lock this mutex ? This would result in any locking at all. You need to share one mutex, declared outside the functions (and don't forget to unlock it afterward, if this is necessary with boost).
You can make the mutex a member variable of the Logger class, and then move the unique_lock inside the write function - this way every call to write will block on the same mutex.
I have finally figured it out. There has to be. thread.join in order to make it execute. Edited my code just in case someone needs it.
I have one question though. Is that a good idea to use locks in that scenario, considering that I there is going to be a lot of log messages during development stage? Am I going to lose performance in that case due to sync?
Yes, you will lose performance - but there's really no good way to do this without locking. (OK, so there's some lock-free queue mechanisms you could use, but they have a lot of complications and require some major sacrifices to work.) The best solution is to log minimally, e.g. provide a "level of detail" flag that can be used to filter out log lines before you lock and try to write them to disk.
I have one question though. Is that a good idea to use locks in that scenario, considering that I there is going to be a lot of log messages during development stage? Am I going to lose performance in that case due to sync?
One way to save performance is to use one log file per thread. Either life with distributed logs or write some tool which merges the logs (timestamp needed in this case).
An other more complicated way is to use one log-buffer per thread and swap it once it is full or after a certain period. A collector thread will gather all full buffers and write them in the correct order out. In this case you would have only few syncronisation points. Thought you must take care in case of a crash. In this case get all buffers and write them out before exiting the application.