Article

From:
To:
Remy Lebeau (TeamB)
Subject:
Re: Thread safety with UnicodeString type [Edit] [Edit]
Newsgroup:
embarcadero.public.cppbuilder.language.cpp

Re: Thread safety with UnicodeString type [Edit] [Edit]

OK here is some example code. It is actually "out of memory" and "invalid pointer operation". The example below works without errors (when Button1 is clicked that is). But if you don't wrap shared variable (SupposedToBeThreadSafe) in ProtectWrite and ProtectRead functions (as in commented lines) you should get errors above.

{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) SupposedToBeThreadSafe = "Is this"; // Uncomment this and comment the one below // else SupposedToBeThreadSafe = "Thread safe"; // Uncomment this and comment the one below
	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 += SupposedToBeThreadSafe + "\r\n"; // Uncomment this and comment the one below
	Txt += ProtectRead() + "\r\n";
	}
//Memo1->Text = Txt;
}
//---------------------------------------------------------------------------
{code}
FYI: Phrase searches are enclosed in either single or double quotes
 
 
Originally created by
Tamarack Associates
Thu, 14 Nov 2024 17:32:09 UTC
Copyright © 2009-2024
HREF Tools Corp.