10 years, 1 month ago.

Thread Local Objects Persist after Termination

I'm encountering a strange problem with local objects in a thread persisting even after the threads destruction. In this case, I have a USB thread that owns a USBHID object like so:

UsbThread.cpp

void USB_Thread(void const *args)
{
    USBHID hid;

    while (true) {
        //Do USB stuff!!
    }
}

Now, one would expect that after terminating that thread or destroying it's Thread class wrapper (which deletes it's stack as well), USBHID would go out of scope and be similarly destroyed. Not so. The USBHID object is persisting somehow and the USB peripheral is continuing to enumerate and work. The only thing that has stopped is the actual communication logic that was in the thread loop.

I thought maybe the USB peripheral could continue to run after being setup, so I did some experiments with the following code snippets:

Automatic Version

if (true) {
    USBHID hid(8, 8);
    led1 = 1;
    wait(5.0);
}
led1 = 0;
while(1);

Heap Version

USBHID* hid = new USBHID(8, 8);
led1 = 1;
wait(5.0);
delete hid;
led1 = 0;
while(1);

In both cases, the USB peripheral disconnects from the host as soon as the USBHID object is destroyed. So why is it persisting in a thread?

1 Answer

10 years, 1 month ago.

You aren't initializing the USBHID object in the first case.

If that's not your actual code, can you show your actual code?

Correct, that's not my actual code. The actual code it too big and complicated to post here, especially since none of it is relevant to the problem. The problem is that the instance of USBHID is not being cleaned up, but staying in memory and (apparently) continuing to service the USB interrupts. Since it's orphaned, I'm suspecting that as soon as I create another thread that allocates a stack in that same area of RAM, mayhem is going to break loose.

posted by Neil Thiessen 21 Mar 2014