Tuesday 15 March 2011

c++ - Multithreaded filestream -


I am creating a client application that connects to a server, and in addition to other features, chat the server in a file Logs that rule violation can be penalized later.
Unfortunately, in the application (at least) two formulas became necessary: ​​the receiver loop and the sender loop - timeliness is required by the server. This means, I need a securely secure solution for data logging in a file.
This can happen, if threads send log information (at most) at the same time:

  Logfile.txt: Chat: Hello My name is Duke chat: Hell [Warning]: Hacker has my name John   

You can inject one sentence to another. I do not want to do this like my std :: cout is similar to the output, but this is not so important.

Question:

  1. How do I Std :: ofstream to log a data at a time?
  2. How do I check if the file was closed by another thread (or error)

    Bonus Questions: Can you solve the same problem for std :: cout ?

    There is no thread safety guarantee in standard currents

    Easiest solution is a mute X is to wrap any statement involving the stream.

      {std :: lock_guard & lt; Std :: mutex & gt; Stopped (gCoutMutex); Std :: cout & lt; & Lt; "This is a message" & lt; & Lt; Std :: endl; }   

    For a more accurate approach, especially a logger, the message should be a logging thread with the queue. When another thread wants to log, it only posts a message in the queue, and the logging thread will go through the queue and write everything on the disk.

    No comments:

    Post a Comment