rust3ds / pthread-3ds

PThread implementation for Nintendo 3DS Horizon OS targets. Keep in mind that Horizon OS uses a cooperative, and not preemptive, threading model.
Apache License 2.0
12 stars 7 forks source link

Call thread-local variable destructors on thread exit #19

Closed AzureMarker closed 4 months ago

AzureMarker commented 2 years ago

Currently we don't call thread local variable destructors when the thread exits. We should probably fix this.

Meziu commented 1 year ago

Those are now called by the default implementation in std

AzureMarker commented 1 year ago

Oh? Do you have a link I can look at?

ian-h-chamberlain commented 1 year ago

Hmm, I thought this would be the case too, since we have "has-thread-local": true in the latest nightly, but I tried to test it using a custom Drop impl in the thread-locals example (with upstream std), and it seems like the destructor isn't running.

I would have expected the dtor to be registered here: https://github.com/rust-lang/rust/blob/master/library/std/src/sys/common/thread_local/fast_local.rs#L52

We might want to reopen this and investigate more; I'm not sure what is the best way to prove that std is doing the right thing, but at minimum we should be able to see a destructor running from a spawned thread (not necessarily the main thread, based on this note from std docs).

Meziu commented 1 year ago

I've done some research, and I've noticed 2 things:

  1. It seems we are actually using the faster thread_local! implementation, so that's nice. This also means that the pthread-3ds impls aren't used (except in register_dtor_fallback, which explicitly uses the OS implementation).
  2. The destructors, registered in register_dtor_fallback, don't run.

It's hard to understand why, even with gdb at hand. It's pretty clear, however, that there isn't much to change in pthread-3ds, since the TLS keys don't originate here (unless it's an issue with the list held by register_dtor_fallback?). Otherwise, it's possible the fallback implementation just doesn't fit Horizon (kernel issues or whatnot), but that's an hypothesis hard to verify.

AzureMarker commented 1 year ago

I'll need to refresh myself on the current state of our thread local implementation, but I thought we had to explicitly call the thread destructors when the thread gets destroyed by us? Around here maybe? https://github.com/rust3ds/pthread-3ds/blob/c885d8cda6d0c5b429b5db3a2408bf204fc1097e/src/thread.rs#L89

Meziu commented 1 year ago

You are correct. I had started looking at the problem with the misconception that std handled the destructors by itself in the thread code, but it's (rightfully so) up to the OS implementation to run them. I've started implementing the changes locally, but it seems I'm getting in all sorts of new errors. I'll publish my work if I manage to get the system working.