{code} //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop
#include "Unit1.h" #include <boost/thread.hpp> //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "IdBaseComponent" #pragma link "IdThreadComponent" #pragma resource "*.dfm" TForm1 *Form1; UnicodeString SupposedToBeThreadSafe; boost::mutex QueueLock; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::FormShow(TObject *Sender) { IdThreadComponent1->Active = true; } //--------------------------------------------------------------------------- void TForm1::ProtectWrite(const UnicodeString &Data) { boost::lock_guard<boost::mutex> lock(QueueLock); SupposedToBeThreadSafe = Data; } //--------------------------------------------------------------------------- UnicodeString TForm1::ProtectRead() { boost::lock_guard<boost::mutex> lock(QueueLock); return SupposedToBeThreadSafe; } //--------------------------------------------------------------------------- void __fastcall TForm1::IdThreadComponent1Run(TIdThreadComponent *Sender) { int i = 0; while (1) {
if (i%2 == 0) ProtectWrite("Is this"); else ProtectWrite("Thread safe"); i++; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { UnicodeString Txt; for (int i = 0; i < 1000; i++) {
Txt += ProtectRead() + "\r\n"; } //Memo1->Text = Txt; } //--------------------------------------------------------------------------- {code}