std::cout und Multithreading
-
So, ich nochmal

in meinem Programm verwende ich Multithreads die jeweils mit cout Daten auf den Bildschirm schreiben.
Allerdings bekomme ich nur Chaos. Mit printf() geht es ohne Probleme, nur sobald ich cout einsetzte, was ich muss,
bekomme ich wirrwarr.sowas zum beispiel:
[9[67 [6.]647 7.5:..4 451V50.e.17r8.5s4.2u.52c202h3 8e8] ]s]: a
:/:V 1 eV2Vre3esr4rus5scu
uhccehhe[ e 6s s7asa./a/40/35019.02723041407.50316083Woran liegt das ? Kann mir das einer erklären und mir vlt sagen wie man das verhindert ?
Danke
-
Das liegt an Multithreading.
-
Das is mir klar,
cout schreibt in stdout, weil aber mehrer Threads laufen, schreibt cout eines anderen Threads mitten in die, gerade von einem anderen Thread augebenen Daten. Aber wieso macht printf das nicht ? Und wie kann man das verhindern ?
-
Hab hier was dazugefunden.
> Can I send output to the std::cout from several threads at the same
> time? Do I have to protect (lock/unlock) it? Which is the best way?cout is thread-safe, in a sense. Each individual output operation is
properly protected. However, doing something like this:// thread 1
cout << data1 << data2 << data3;
// thread 2
cout << data4 << data5 << data6;can produce output where the data elements from different threads are
randomly interleaved. Very likely this is not what you want. Which
usually means you need to introduce your own locking anyway.Das heißt ich muss vor der Ausgabe den stdout exclusiv für diesen cout sperren
und nach der Ausgabe wieder entsperren.Nur wie mach ich das lock/unlock ?
-
mutex
-
oder CriticalSections
http://www.c-plusplus.net/forum/viewtopic-var-t-is-123455-and-highlight-is-.html