Search code examples
multithreadingoperating-systemsystemdeadlock

When does a thread die?


As a student in CS, I study the almost every concepts from textbooks.

I've known that the bad situations may occur when a thread dies.

But I want to know when a thread can die accidentally.

When can it happen in real world?

Let me hear your real experience.

** I've came up with this question when I read that a bad thing may happen when a thread dies accidentally with holding a lock.


Solution

  • A thread should die when it runs out of things to do. In every thread framework I've ever seen, you tell a thread what to do by providing a function that the framework will call one time from within the thread.

    When that function returns (either by a normal return or by throwing an uncaught exception), that tells the framework that there's nothing left for the thread to do, and so the framework kills the thread.

    In some frameworks, especially in cases where the language does not have any non-local exit mechanism (i.e., exceptions), the framework will also provide a function that a thread can call to explicitly kill itself.


    I want to know when a thread can die accidentally

    From the perspective of the library developer or the OS developer, that can't happen. If a thread could die "by accident," then that would be a serious defect in the library and/or the OS.

    Your code might accidentally do something that you did not want it to do. That also is a defect, but the defect is yours to find and fix.

    • If your defect results in an uncaught exception, then the framework probably will kill just the one thread, or it might kill the whole process. There's not much else it could do: You can't expect the library author to know how to handle and recover from any arbitrary exception in any arbitrary program.
    • If your defect results in a hardware fault (e.g., attempt to read or write an invalid memory address) then it's pretty much the same story. The OS might respond by raising an exception in your thread (in which case, see above) or it might skip right to the part where it kills the thread or the whole process.
    • If your defect results in some other behavior (e.g., deadlock, infinite loop,...) then the thread probably will not die until you intervene by sending the process a signal, etc.