Board index » cppbuilder » Persist __declspec(thread) variables for Synchronize()

Persist __declspec(thread) variables for Synchronize()


2005-01-31 10:24:50 AM
cppbuilder7
Dear all,
In a thread's implementation, I declare a char string as global variable
with __declspec(thread) modifier, in an attempt to make it unique to each
thread instance:
__declspec(thread) char szProcBuffer[512];
However it seems does not work as the char string becomes null when it is
referenced in the Synchronize() function.
void __fastcall TClientThread::InsertOutputRecord(void)
{
try
{
MainForm->Table1->FieldByName("Msg")->AsString =
AnsiString(szProcBuffer); // The string becomes null here
MainForm->Table1->FieldByName("Rcvd_Time")->AsDateTime = Now();
MainForm->Table1->Post();
}
catch(Exception &E)
{
...
}
}
Is it a correct perception for my use of the modifier? Or there are some
other details I have not accounted for?
Thanks for any kind advice.
Patrick
 
 

Re:Persist __declspec(thread) variables for Synchronize()

"Patrick Wong" < XXXX@XXXXX.COM >wrote in message
Quote
In a thread's implementation, I declare a char string as global
variable with __declspec(thread) modifier, in an attempt to
make it unique to each thread instance:

__declspec(thread) char szProcBuffer[512];
Rather than using a global variable, just make the variable be a member of
your thread class instead:
class TClientThread : public TThread
{
private:
char szProcBuffer[512];
//...
};
Quote
However it seems does not work as the char string becomes null
when it is referenced in the Synchronize() function.
By using __declspec(thread), every thread will have its own unique copy of
the variable. The method that is called by Synchronize() is run in the
context of the main VCL thread, not your worker thread, so the method will
be accessing the main thread's copy of the variable, which you did not ever
assign a value to.
Gambit
 

Re:Persist __declspec(thread) variables for Synchronize()

"Remy Lebeau (TeamB)" < XXXX@XXXXX.COM >wrote in message
Quote

"Patrick Wong" < XXXX@XXXXX.COM >wrote in message
news:41fd96f1$ XXXX@XXXXX.COM ...

Rather than using a global variable, just make the variable be a member of
your thread class instead:

class TClientThread : public TThread
{
private:
char szProcBuffer[512];
//...
};

It works, thanks.
Quote

By using __declspec(thread), every thread will have its own unique copy of
the variable. The method that is called by Synchronize() is run in the
context of the main VCL thread, not your worker thread, so the method will
be accessing the main thread's copy of the variable, which you did not
ever
assign a value to.


Does it mean even I acquire thread local storage by TlsAlloc(),
TlsSetValue(), TlsGetValue() etc., the variable is not meaningful if being
Synchronize() in main thread's context? Require your elaboration here.
 

{smallsort}