Is there an invalid pthread_t id?

前端 未结 6 2022
说谎
说谎 2020-12-13 05:43

I would like to call pthread_join for a given thread id, but only if that thread has been started. The safe solution might be to add a variable to track which thread where s

6条回答
  •  时光说笑
    2020-12-13 06:15

    This is an excellent question that I really wish would get more discussion in C++ classes and code tests.

    One option for some systems-- which may seem like overkill to you, but has come in handy for me-- is to start a thread which does nothing other than efficiently wait for a tear-down signal, then quit. This thread stays running for the life of the application, going down very late in the shutdown sequence. Until that point, the ID of this thread can effectively be used as an "invalid thread" value-- or, more likely, as an "uninitialized" sentinel-- for most purposes. For example, my debug libraries typically track the threads from which mutexes were locked. This requires initialization of that tracking value to something sensible. Because POSIX rather stupidly declined to require that platforms define an INVALID_THREAD_ID, and because my libraries allow main() to lock things (making the pthread_self checks that are a good solution pthread_create unusable for lock tracking), this is the solution I have come to use. It works on any platform.

    Note, however, that you have a little more design work to do if you want this to be able to initialize static thread references to invalid values.

提交回复
热议问题