views:

102

answers:

2

I'm trying to clean up specific memory objects created by a specific thread (hence only accessible to that thread). The only way for me to achieve that is to switch to that particular thread when freeing that memory block.

This is how I allocated the specific memory context:

This is what I attempted to do:

alt text

I have originally added the memory context creation and destruction in a manner like the following:

int Thread2::main()
{
     CudaMemoryContext *theCudaObj = new CudaMemoryContext();
     while(!TerminateStatus())
     {
        ...
     }
     delete theCudaObj;
     return 0;
}

However, this approach is not working very well, i.e. the program crashes right when I'm cleaning up on the "delete theCudaObj;" line. I'm wondering if I can switch active threads when cleaning up, or allocate the CUDA context to be accessible by both threads so that I can clean up and access it with ease through both threads. Thanks in advance for suggestions.

+1  A: 

How is Thread#1 destroying Thread#2? It's typically best to signal a thread to terminate itself and not use TerminateThread().

Thread #1's destructor is requesting thread #2 to be terminated by setting a flag for thread #2's main loop to detect. What would be the best way to signal a thread though? Creating another semaphore or a separate mailbox for this purpose?
stanigator
Hopefully thread#2's loop is designed to block waiting on some kind of event, otherwise it will be chewing up CPU cycles needlessly. Create an additional event which is signaled by Thread1 before it exits. Thread1 then calls WaitForSingleEvent(hThread2) before exiting which ensures that Thread2 has properly terminated.
I have briefly looked over the example shown in http://msdn.microsoft.com/en-us/library/ms686915%28VS.85%29.aspxHowever, I'm not sure if this is the easiest example to figure out what's going on with using events. Do you have any recommendations on certain examples?
stanigator
Search for MVP Tips, Techniques, and Goodies by Joseph Newcomer. Lots of MFC specific stuff including threads.
A: 

Your original approach looks like the right way to go about things - when the thread is signaled to terminate it stops looping and cleans up any allocated memory.

In the context where you signal a thread to terminate, be sure you wait for it to exit before allowing the application to exit. Premature exit could have been causing your crash. Run with the debugger attached and set to break when exceptions are thrown to diagnose.

Aidan Ryan