pthread_cleanup_pop() — Remove a cleanup handler

Standards

Standards / Extensions C or C++ Dependencies

POSIX.4a
Single UNIX Specification, Version 3

both

POSIX(ON)

Format

#define _OPEN_THREADS
#include <pthread.h>

void pthread_cleanup_pop(int execute);

General description

Removes the specified routine in the last executed pthread_cleanup_push() statement from the top of the calling thread's cleanup stack.

The execute parameter specifies whether the cleanup routine that is popped should be run or just discarded. If the value is nonzero, the cleanup routine is executed.

pthread_cleanup_push() and pthread_cleanup_pop() must appear in pairs in the program within the same lexical scope, or undefined behavior will result.

When the thread ends, all pushed but not yet popped cleanup routines are popped from the cleanup stack and executed in last-in-first-out (LIFO) order. This occurs when the thread:
  • Calls pthread_exit()
  • Does a return from the start routine (that gets controls as a result of a pthread_create())
  • Is canceled because of a pthread_cancel()

Returned value

pthread_cleanup_pop() returns no values.

This function is used as a statement.

If an error occurs while a pthread_cleanup_pop() statement is being processed, a termination condition is raised.

There are no documented errno values. Use perror() or strerror() to determine the cause of an error.

Example

CELEBP15
⁄* CELEBP15 *⁄
#define _OPEN_THREADS
#include <pthread.h>
#include <stdio.h>

int iteration;

void noise_maker(void *arg) {
  printf("hello from noise_maker in iteration %d!\n", iteration);
}

void *thread(void *arg) {
  pthread_cleanup_push(noise_maker, NULL);
  pthread_cleanup_pop(iteration == 1 ? 0 : 1);
}

main() {
  pthread_t thid;
  void * ret;

  for (iteration=1; iteration<=2; iteration++) {

    if (pthread_create(&thid, NULL, thread, NULL) != 0) {
      perror("pthread_create() error");
      exit(1);
    }

    if (pthread_join(thid, &ret) != 0){
      perror("pthread_join() error");
      exit(2);
    }
⁄*
    if (pthread_detach(&thid) != 0) {
      perror("pthread_detach() error");
      exit(3);
    }
 *⁄
  }
}
Output:
hello from noise_maker in iteration 2!

Related information