Re: writing thread safe / reenterent code (c++)
On Thu, 15 Jan 2009 21:48:00 -0800, sachin
<sachin@discussions.microsoft.com> wrote:
Is following code a thread safe routine
callme()
{
char* ptr = new char[10];
strcpy(ptr,"c++");
callhim(ptr);
}
callhim(char* ptr)
{
char* second = new char[10];
strcpy(second , ptr);
cout<<ptr;
}
I feel both of the functions are not thread safe .. nor reenternt ..
local memory allocation using heap makes the routine thread unsafe and non
reenterent ..
Am i right ?
No. Access to the heap is synchronized in programs that use the
multithreaded CRT. Ditto for the cout statement. However, if you had
written the following, you could observe interleaved output because the
statement isn't locked as a whole:
cout << x << y;
That is, two threads executing this concurrently could print the following,
where x1 and y1 are printed by thread 1 and x2 and y2 by thread2:
x1
x2
y1
y2
There are other possibilities, and the one thing that is guaranteed is that
x will be printed before y for each thread executing the statement.
P.S. The memory leaks, exception-unsafe code, use of implicit int, etc
weren't relevant to your question, so I ignored these things. If you don't
know what I mean, please say so.
--
Doug Harrison
Visual C++ MVP