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
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_ptrin MSVC’s standard library it’s protected automatically).