> (me using visual c++ 2005, all native/unmanaged).
So my question is about allocating memory in one thread and using it in
another.
I think its good to explain as following :
Somewhere I have this:
someclass * _obj;
thread_proc1() //used by thread1
{
// this thread does the following:
_obj = new someclass();
.......
// thread exits, but does not delete _obj....
}
thread_proc2() // used by thread 2
{
/* this thread starts later on and plays around
with _obj object that was allocated in thread 1 */
}
I want to know is all this ok? I just had a confusion that bcuz the _obj
variable was declared in thread1 I may have some problem accessing it in
thread 2 after thread 1 is finished. But on the other hand I thought that
since _obj was allocated in the process heap, which wont deallocate when
thread1 exits, so it should be ok for thread 2. And thread 2 can even delete
it. Am I write in thinking of the process's heap this way?
You are right in your assumptions, but programming like this is dangerous.
you have to think of the following scenarios:
- what happens if thread2 runs first?
- what happens if thread1 runs twice before thread2 runs?
- what happens if thread1 and thread2 are running at the same time?
- ...
if you wait with starting thread2 until thread1 has finished, the advantages
of multithreading are gone too.
even if you start thread2 after thread1, there is no guarantee that thread1
will be running when thread2 starts running. that depends on scheduling.
it would be better to new the object in your program initialization, and
then delete it after all threads have run.
What you do of course depends on what you want your application to do, but
assuming that things have happened in 1 thread before something else happens
in another thread is asking for hard to find runtime problems.
--
Kind regards,
Bruno.
br**********************@hotmail.com
Remove only "_nos_pam"