-
January 16th, 2009, 12:40 AM
#1
Thread Safe code
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;
}
-
January 16th, 2009, 02:00 AM
#2
Re: Thread Safe code
Are they executing in the same thread, or different threads? Where is the memory deleted?
-
January 16th, 2009, 02:13 AM
#3
Re: Thread Safe code
they are in the same library and the library is being used in multithread environment
Please neglect any memory leak issues in the program ..
i main concern is
1. if function is allocating memory on heap is he thread safe
-
January 16th, 2009, 02:59 AM
#4
Re: Thread Safe code
Just ask yourself this question:
Can the resource shared between threads be accessed concurrently where one or more threads are writing to the resource?
If the answer is yes, then it's not thread safe.
-
January 16th, 2009, 03:57 AM
#5
Re: Thread Safe code
Originally Posted by sachinchakote
1. if function is allocating memory on heap is he thread safe
You cannot tell generally. If many threads read from the same memory there's never a problem. But if some threads write while other threads read at the same time, or if many threads write at the same time, it's not threadsafe. In these cases memory access must be synchronized.
So it's the usage that matters, not where the memory is allocated.
Last edited by _uj; January 16th, 2009 at 04:40 AM.
-
January 16th, 2009, 07:04 AM
#6
Re: Thread Safe code
From Wikipedia:
Originally Posted by Wikipedia
A computer program or routine is described as reentrant if it can be safely executed concurrently; that is, the routine can be re-entered while it is already running. To be reentrant, a computer program or routine:
- Must hold no static (global) non-constant data.
- Must not return the address to static (global) non-constant data.
- Must work only on the data provided to it by the caller.
- Must not rely on locks to singleton resources.
- Must not call non-reentrant computer programs or routines.
Multiple levels of 'user/object/process priority' and/or multiprocessing usually complicate the control of reentrant code. Also, IO code is usually not reentrant because it relies on shared, singleton resources such as disks.
-
January 16th, 2009, 07:34 AM
#7
Re: Thread Safe code
Ignoring the non-initialised char array you are strcpying to, the routines look thread safe, except...
cout<<ptr;
If one thread is part way through executing this line and another preempts it, you may not get what you expect on the screen.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|