I have overloaded <<
operator such that it write to file and also on the console. I have created 8 threads to the same function, and I want to output
hello
hi
If I run this thread routine in an infinite loop th开发者_运维百科e o/p in the file is
hello
hi
hello
hi
hello
hi
ello
i
hello
hi
hello
hi
llo
i
hello
hi
This has no pattern. What is the problem? I am able to print it properly on console but not into a file.
Are you locking a mutex when you are sending data to a stream? The c++ stream classes are not thread-safe.
Create a queue and write to it. Dequeue queue in desired granularity - one line for example (I guess that that's what you want from your example).
Something like:
CRITICAL_SECTION cs;
list<string> _queue;
void Write(string line)
{
EnterCriticalSection(&cs);
_queue.push_back(line);
LeaveCriticalSection(&cs);
}
ThreadProc()
{
while (!_shouldStop)
{
Dequeue();
Sleep(100);
}
}
void Dequeue()
{
EnterCriticalSection(&cs);
if (!_queueIsEmpty())
{
string line=_queue.front();
_queue.pop_front();
stream << line;
}
LeaveCriticalSection(&cs);
}
This is not C code - this is just a example, there are lot's of other things to have in mind, just to name few of them:
- your granularity might vary, I used line here
- you might want to use dequeue<> or some similar FIFO structure
- you might want to
WaitForSingleObject()
instead ofSleep()
-ing to have better control for cases when you want to stop - create singleton object for the stuff and use it where you need it (I guess that you are creating some kind of logging facility?)
Actually you have a problem of synchronization between thread.
For example with 2 thread: (cout of a string is representing by "print" character).
thread1 thread2
print h
print e
print l
print h
print l
print o
print e
print \n
print l
print l
print o
print \n
the result will be:
helhloe
llo
you need to make sure that your function is not used by two thread at the same time.
function_cout_hello()
lock()
file << ...
unlock()
like that, two different thread can not use the function at the same time.
精彩评论