A detailed explanation of Pthread_cleanup_push ()/pthread_cleanup_pop ()

Source: Internet
Author: User
Tags posix terminates

Just practice the thread of the condition variable encountered these two functions, about the two functions of the book is relatively vague, so found a piece of the internet I feel good about an article, is about the termination of the thread, probably as follows:
In general, POSIX thread termination has two conditions: normal and abnormal termination. A thread that actively invokes Pthread_exit () or return from a thread function causes the thread to exit normally. This is a predictable exit mode, and an abnormal termination is not foreseen when the thread exits with the intervention of another thread, or because of an error in its own operation, such as access to an illegal address.

Whether it is a predictable thread termination or abnormal termination, there will be the issue of resource release, without considering the failure to exit due to the operation of the premise, how to ensure that the thread termination can smoothly release the resources occupied by their own, especially lock resources, is a must be considered to solve the problem.

The most common scenario is the use of resource exclusive locks: Threads are locked for access to critical resources, but are canceled during the access process, if the thread is in a response-cancellation state, respond asynchronously, or have a cancellation point on the run path prior to opening the exclusive lock. The critical resource is permanently locked out of the lock state. Outside cancellation is unpredictable, so it does require a mechanism to simplify programming for resource release.

A Pthread_cleanup_push ()/pthread_cleanup_pop () function is provided in the POSIX thread API to automatically release resources-from the call point of Pthread_cleanup_push () to Pthread_ The termination action in the program segment between Cleanup_pop (), including the call to Pthread_exit () and the cancellation point termination, performs the cleanup function specified by Pthread_cleanup_push (). The API is defined as follows:

void Pthread_cleanup_push (void (*routine) (void  *),  void *arg)
void Pthread_cleanup_pop (int execute)

Pthread_cleanup_push ()/pthread_cleanup_pop () is managed by the first-in-out stack structure, and the void routine (void *arg) function calls Pthread_cleanup_push () When pressed into the cleanup function stack, multiple calls to the Pthread_cleanup_push () will form a function chain in the cleanup function stack, which pops up in the reverse order of the stack when the function chain is executed. The Execute parameter indicates whether execution to Pthread_cleanup_pop () executes the function while the cleanup function is ejected, 0 for not executing, not 0 for execution, and this parameter does not affect execution of the cleanup function when the exception terminates.

The Pthread_cleanup_push ()/pthread_cleanup_pop () is implemented in a macro way, which is the macro definition in Pthread.h:

#define Pthread_cleanup_push (Routine,arg)
{struct _pthread_cleanup_buffer _buffer;
_pthread_cleanup_push (&_buffer, (routine), (ARG));
#define PTHREAD_CLEANUP_POP (Execute)
_pthread_cleanup_pop (&_buffer, (execute)); }
Visible, Pthread_cleanup_push () with a "{", and Pthread_cleanup_pop () with a "}", so the two functions must appear in pairs, and must be at the same level of the program code snippet to compile. In the following example, when the thread terminates in "Do some work", the Pthread_mutex_unlock (Mut) is invoked actively to complete the unlock action.
Work, Pthread_mutex_unlock (Mut) will be invoked actively to complete the unlock action when terminated.
Pthread_cleanup_push (Pthread_mutex_unlock, (void *) &mut);
Pthread_mutex_lock (&mut);
/* Do some work * *
Pthread_mutex_unlock (&mut);
Pthread_cleanup_pop (0);
It is important to note that if the thread is in a pthread_cancel_asynchronous state, the code snippet above can be faulted because the CANCEL event may be
Occurs between Pthread_cleanup_push () and Pthread_mutex_lock (), or between Pthread_mutex_unlock () and Pthread_cleanup_pop (), Which causes the cleanup function to unlock one that is not locked.
Mutex variable, resulting in an error. Therefore, when using the cleanup function, it should be temporarily set to pthread_cancel_deferred mode. For this reason, POSIX's
The Linux implementation also provides a pair of pthread_cleanup_push_defer_np ()/pthread_cleanup_pop_defer_np () extension functions that are not guaranteed to be portable, with the following
The code snippet is equivalent:
{int oldtype;
Pthread_setcanceltype (pthread_cancel_deferred, &oldtype);
Pthread_cleanup_push (routine, ARG);
...
Pthread_cleanup_pop (execute);
Pthread_setcanceltype (Oldtype, NULL);
}
The part I marked with red above is the key role of these two functions, and my understanding is:
Pthread_cleanup_push (Pthread_mutex_unlock, (void *) &mut);
Pthread_mutex_lock (&mut);
/* Do some work * *
Pthread_mutex_unlock (&mut);
Pthread_cleanup_pop (0);
Originally do some work is followed by Pthread_mutex_unlock (&mut), which means that there is a unlock operation, but there will be abnormal termination in do some work, in which case the system will be based on Pthread_cleanup_ The functions provided in the push, and the parameters to unlock the operation or other operations, so as not to cause deadlock!

Supplemental:
The active call return in the thread host function, if the return statement is contained in Pthread_cleanup_push ()/pthread_cleanup_pop (), does not cause the cleanup function to execute. But it will lead to segment fault.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.