littlekernel / lk

LK embedded kernel
MIT License
3.13k stars 614 forks source link

thread_join on a thread from multiple threads #35

Open jaybh opened 9 years ago

jaybh commented 9 years ago

Is the behaviour undefined for when a thread is joined by multiple concurrent threads ?

From the man-page of pthread, I realize they do it that way.

And from kernel/thread.c it seems, we do the same. In fact we will invariably crash, since we call wait_queue_wake_all from thread_detach / thread_exit. Hence multiple threads will be trying to free the resources of the thread.

Is that a valid observation ?

travisg commented 9 years ago

Looks like it. From glancing at it it could probably be fixed by using wake_queue_wake_one() in the thread_exit with the return code 0. Then, in the cleanup path in thread_join(), hit the wait queue with wake_queue_wake_all() with a nonzero return code, so that any other thread waiting will unblock but not try to clean it up.

It would have the property that only one of the threads would get the return code and the others would get an error message. Not super ideal, but at least it wouldn't crash.

jaybh commented 9 years ago

Exactly. We somehow need to wake up one thread (with a different error code that suggests cleanup the resources) and then the others (which should not cleanup the resources)

The other solution I can think of is, to check whether the thread data structure already exists in thread_join itself. If not null, then call free(). Or even better, reference count it.