简体   繁体   中英

pthread_exit() from within a function

I have a multithreaded program, the threads do work which can take a relatively long time.

If I want to stop the execution of the program I have an atomic switch which I change from 0 to 1 which would signal a thread that it should exit. This currently gets checked in a while loop.

However an iterations of the while loop can take quite a long time. Now I want basically define a few 'gracefull' exit points within the while loop.

basically I would define a short macro like this, where ks is the switch:

#define GRACE_EXIT(ks) \
    if (__atomic_load_n(ks, __ATOMIC_SEQ_CST) == 1) \
        pthread_exit(NULL);

Now I wonder if it is allowed to call this from functions that I call from within the thread.

basically within the while loop I call various function. The basic question I am having is if it is allowed to call pthread_exit() from within functions which is not the entry point of the thread. the 2nd concern I have is of the cleanup of the automatic variables that are not within the scope of the calling function.

let`s say I am 4 functions 'deep' and call this macro. Are all the automatic variables cleaned up even if they are not within scope?

You can safely call pthread_exit() from anywhere in the thread as long as the thread is then joined or was detached. However any handles and memory you allocated or you own, will not get released.

The pthread_exit() function shall terminate the calling thread and make the value value_ptr available to any successful join with the terminating thread. Any cancellation cleanup handlers that have been pushed and not yet popped shall be popped in the reverse order that they were pushed and then executed. After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions shall be called in an unspecified order. Thread termination does not release any application visible process resources, including, but not limited to, mutexes and file descriptors, nor does it perform any process-level cleanup actions, including, but not limited to, calling any atexit() routines that may exist.

The only exceptions are:

The behavior of pthread_exit() is undefined if called from a cancellation cleanup handler or destructor function that was invoked as a result of either an implicit or explicit call to pthread_exit().

So you have foo that you use as the main function of a thread, and then inside foo you call bar , which inside that has pthread_exit(NULL); ? Should work fine.

This is mainly for other people: If you open a new thread in that thread to exit the first thread, no it will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM