views:

102

answers:

3

I'm trying to multithread something and i have my program set up such that i have a structure/class of variables that will be passed into each thread for processing.

In this class, there are variables that hold pointers to arrays some threads have common arrays from which they read data off of, instead of duplicating those arrays, pointers are given to each function that direct them to one array. These common arrays are initialized in the main program and then the variables in an array of classes are pointed to that array which is then in turn passed off to a thread.

My question is at which level (main program or thread) should i use the delete command to terminate that array? Also, what happens to the other pointers when i do that? are they automatically deleted as well or do i have to manually keep track of those. Lastly, what happens if i accidentally delete an array while another thread is still using it?

Thanks,

-Faken

+1  A: 

If you delete an array which other thread is still using, you get undefined behaviour, mist probably a crash.

For your case I would recommend to clean up in the main thread, after all the worker threads are finished.

Another possibility would be to use a shared pointer, which would automatically free the resources as soon as no thread is using them (though beware that you need to protect your access to the shared pointer -- for shared_ptr in MSVC's standard library it's protected automatically).

Vlad
+1  A: 

delete does not modify the pointer, but makes the memory being pointed to unuseable.

So once some memory is deleted, you cannot reference it. This is just as true for a single pointer as multiple pointers:

You can use shared pointers that will use reference counting so that the underlying memory will only be deleted when all pointers are released. For your example, you need to make sure the shared pointers are thread safe.

R Samuel Klatchko
A: 

all variable inside a process (application) are shared across threads, any modification to a variable or memory will have effect to all threads that have access to it, unless you are using thread local storage (TLS).

If you delete an array, then another thread using it, the result will be like when you delete an array then you re-access it somewhere in your code (mostly crash due to access violation).

as for "which level" question, i think it is better to deallocate an object by the thread which create the object to avoid confusion, and be sure that those objects are no longer needed by another thread.

uray