pthread_cleanup_pushのヘルプ・マニュアル
日本語 英語
pthread_cleanup_push --help
man pthread_cleanup_push
PTHREAD_CLEANUP(3) PTHREAD_CLEANUP(3)
名前
pthread_cleanup_push, pthread_cleanup_pop,
pthread_cleanup_push_defer_np, pthread_cleanup_pop_restore_np - クリ ー
ンアップハンドラを登録および削除する
書式
#include
void pthread_cleanup_push(void (*routine) (void *), void *arg);
void pthread_cleanup_pop(int execute);
void pthread_cleanup_push_defer_np(void (*routine) (void *), void
*arg);
void pthread_cleanup_pop_restore_np(int execute);
説明
クリーンアップハンドラは、 pthread_exit(3) が呼び出されたり、取り消しさ
れ たりしてスレッドが終了するときに呼び出される関数である。クリーンアッ
プハンドラはスタック風の規則にならって登録および削除される。
クリーンアップハンドラの目的は、スレッドが終了するときに保持している か
もしれない資源を解放することである。殊に、スレッドがロック中の mutex を
保持したまま終了したり取り消しされたりすると、その mutex は永久にロック
さ れたままで、ほかのスレッドが正常に実行できなくなってしまう。このこと
を防ぐ最もよい方法は、 mutex をロックする直前に、 mutex のロックを解 除
す るためのクリーンアップハンドラを登録することである。同じように、クリ
ーンアップハンドラはスレッドの終了時に malloc(3) で確保されたメモリブロ
ッ クを解放したりファイルディスクリプターをクローズしたりするのに使用で
きる。
pthread_cleanup_push は関数 routine を引数 arg とともにクリーンアップハ
ンドラとして登録する。この時点から対応する pthread_cleanup_pop までの間
、そのスレッドが pthread_exit(3) または取り消しによって終了する時に、関
数 routine が引数 arg をともなって呼び出されるようになる。終了する時点
で複数のクリーンアップハンドラが有効になっている場合は、クリーンアッ プ
ハ ンドラは LIFO 順に呼び出される: すなわち、最後に登録されたハンドラが
最初に呼び出される。
pthread_cleanup_pop は、最後に登録されたクリーンアップハンドラを削除 す
る。引数 execute が 0 でない場合、 pthread_cleanup_pop はハンドラを実行
する。すなわち、関数 routine を引数 arg をともなって呼び出す。引数 exe-
cute が 0 の場合は、ハンドラが削除されるだけで、実行されることはない。
対応する pthread_cleanup_push と pthread_cleanup_pop の対は、同じ関数内
の、同じブロック階層になければならない。実際、 pthread_cleanup_push と
pthread_cleanup_pop はマクロであり、 pthread_cleanup_push のマクロ展開
には開き括弧 { が含まれていて、それに対応する閉じ括弧 } は、対 応 す る
pthread_cleanup_pop のマクロ展開に含まれている。
pthread_cleanup_push_defer_np は、 pthread_cleanup_push と pthread_set-
canceltype(3) を組み合わせた、ポ ー タ ブ ル で な い 拡 張 で あ る 。
pthread_cleanup_push とまったく同じようにクリーンアップハンドラを登録す
るが、同時にその時点の取り消し型を保存し、取り消し型を遅 延 (deferred)
に 変 更する。これによって、スレッドの取り消し型が非同期 (asynchronous)
であってもクリーンアップ機構が有効になることが保証される。
pthread_cleanup_pop_restore_np は pthread_cleanup_push_defer_np によ っ
て 登 録 さ れ た は ク リ ー ン ア ッ プハンドラを削除し、取り消し型を
pthread_cleanup_push_defer_np が呼び出された時点の値に戻す。
pthread_cleanup_push_defer_np と pthread_cleanup_pop_restore_np は対 に
なっていなければならず、ともに同じブロック階層になければならない。
pthread_cleanup_push_defer_np(routine, arg);
pthread_cleanup_pop_defer_np(execute);
の よ うな流れは機能的に次のものと同等 (だがよりコンパクトでより効率的)
である。
{ int oldtype;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
pthread_cleanup_push(routine, arg);
...
pthread_cleanup_pop(execute);
pthread_setcanceltype(oldtype, NULL);
}
返り値
なし。
エラー
なし。
著者
Xavier Leroy
関連項目
pthread_exit(3), pthread_cancel(3), pthread_setcanceltype(3).
例
次の例は、 mutex mut をロック中にスレッドが取り消しされたらロックを解除
するように、 mutex mut をロックする方法である:
pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
/* 何かをする */
pthread_mutex_unlock(&mut);
pthread_cleanup_pop(0);
最後の 2 行は次のものと同等で、置き換えが可能である:
pthread_cleanup_pop(1);
上 のコードは取り消し型が遅延 (deferred) である場合に限って安全であるこ
とに注意すること ( pthread_setcanceltype(3) を参照 ) 。取り消し型が非同
期 (asynchronous) の場合には、スレッドの取り消しが pthread_cleanup_push
と pthread_mutex_lock の 間 や 、 pthread_mutex_unlock と
pthread_cleanup_pop の間で起こる可能性があり、どちらの場合にもスレッド
はカレントスレッドでロックしていない mutex をロック解除しようとしてしま
う。このことは非同期取り消しが使いにくいことの主な理由である。
上のコードが非同期取り消し型でも動作しなければならない場合、 mutex のロ
ックおよびロック解除のために、取り消し型を遅延 (deferred) に変更しな け
ればならない:
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
/* do some work */
pthread_cleanup_pop(1);
pthread_setcanceltype(oldtype, NULL);
上 の コ ー ドは、ポータブルでない関数 pthread_cleanup_push_defer_np と
pthread_cleanup_pop_restore_np を使うことで、よりコンパクトでより効率的
な方法に書き直すことができる:
pthread_cleanup_push_restore_np(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
/* do some work */
pthread_cleanup_pop_restore_np(1);
LinuxThreads PTHREAD_CLEANUP(3)
PTHREAD_CLEANUP_PUSH(3) Linux Programmer’s Manual PTHREAD_CLEANUP_PUSH(3)
NAME
pthread_cleanup_push, pthread_cleanup_pop - push and pop thread cancel-
lation clean-up handlers
SYNOPSIS
#include
void pthread_cleanup_push(void (*routine)(void *),
void *arg);
void pthread_cleanup_pop(int execute);
Compile and link with -pthread.
DESCRIPTION
These functions manipulate the calling thread’s stack of thread-cancel-
lation clean-up handlers. A clean-up handler is a function that is
automatically executed when a thread is canceled (or in various other
circumstances described below); it might, for example, unlock a mutex
so that it becomes available to other threads in the process.
The pthread_cleanup_push() function pushes routine onto the top of the
stack of clean-up handlers. When routine is later invoked, it will be
given arg as its argument.
The pthread_cleanup_pop() function removes the routine at the top of
the stack of clean-up handlers, and optionally executes it if execute
is non-zero.
A cancellation clean-up handler is popped from the stack and executed
in the following circumstances:
1. When a thread is canceled, all of the stacked clean-up handlers are
popped and executed in the reverse of the order in which they were
pushed onto the stack.
2. When a thread terminates by calling pthread_exit(3), all clean-up
handlers are executed as described in the preceding point. (Clean-
up handlers are not called if the thread terminates by performing a
return from the thread start function.)
3. When a thread calls pthread_cleanup_pop() with a non-zero execute
argument, the top-most clean-up handler is popped and executed.
POSIX.1 permits pthread_cleanup_push() and pthread_cleanup_pop() to be
implemented as macros that expand to text containing '{' and '}',
respectively. For this reason, the caller must ensure that calls to
these functions are paired within the same function, and at the same
lexical nesting level. (In other words, a clean-up handler is only
established during the execution of a specified section of code.)
Calling longjmp(3) (siglongjmp(3)) produces undefined results if any
call has been made to pthread_cleanup_push() or pthread_cleanup_pop()
without the matching call of the pair since the jump buffer was filled
by setjmp(3) (sigsetjmp(3)). Likewise, calling longjmp(3) (sig-
longjmp(3)) from inside a clean-up handler produces undefined results
unless the jump buffer was also filled by setjmp(3) (sigsetjmp(3))
inside the handler.
RETURN VALUE
These functions do not return a value.
ERRORS
There are no errors.
CONFORMING TO
POSIX.1-2001.
NOTES
On Linux, the pthread_cleanup_push() and pthread_cleanup_pop() func-
tions are implemented as macros that expand to text containing '{' and
'}', respectively. This means that variables declared within the scope
of paired calls to these functions will only be visible within that
scope.
POSIX.1 says that the effect of using return, break, continue, or goto
to prematurely leave a block bracketed pthread_cleanup_push() and
pthread_cleanup_pop() is undefined. Portable applications should avoid
doing this.
EXAMPLE
The program below provides a simple example of the use of the functions
described in this page. The program creates a thread that executes a
loop bracketed by pthread_cleanup_push() and pthread_cleanup_pop().
This loop increments a global variable, cnt, once each second. Depend-
ing on what command-line arguments are supplied, the main thread sends
the other thread a cancellation request, or sets a global variable that
causes the other thread to exit its loop and terminate normally (by
doing a return).
In the following shell session, the main thread sends a cancellation
request to the other thread:
$ ./a.out
New thread started
cnt = 0
cnt = 1
Canceling thread
Called clean-up handler
Thread was canceled; cnt = 0
From the above, we see that the thread was canceled, and that the can-
cellation clean-up handler was called and it reset the value of the
global variable cnt to 0.
In the next run, the main program sets a global variable that causes
other thread to terminate normally:
$ ./a.out x
New thread started
cnt = 0
cnt = 1
Thread terminated normally; cnt = 2
From the above, we see that the clean-up handler was not executed
(because cleanup_pop_arg was 0), and therefore the value of cnt was not
reset.
In the next run, the main program sets a global variable that causes
the other thread to terminate normally, and supplies a non-zero value
for cleanup_pop_arg:
$ ./a.out x 1
New thread started
cnt = 0
cnt = 1
Called clean-up handler
Thread terminated normally; cnt = 0
In the above, we see that although the thread was not canceled, the
clean-up handler was executed, because the argument given to
pthread_cleanup_pop() was non-zero.
Program source
#include
#include
#include
#include
#include
#include
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
static int done = 0;
static int cleanup_pop_arg = 0;
static int cnt = 0;
static void
cleanup_handler(void *arg)
{
printf("Called clean-up handler\n");
cnt = 0;
}
static void *
thread_start(void *arg)
{
time_t start, curr;
printf("New thread started\n");
pthread_cleanup_push(cleanup_handler, NULL);
curr = start = time(NULL);
while (!done) {
pthread_testcancel(); /* A cancellation point */
if (curr < time(NULL)) {
curr = time(NULL);
printf("cnt = %d\n", cnt); /* A cancellation point */
cnt++;
}
}
pthread_cleanup_pop(cleanup_pop_arg);
return NULL;
}
int
main(int argc, char *argv[])
{
pthread_t thr;
int s;
void *res;
s = pthread_create(&thr, NULL, thread_start, NULL);
if (s != 0)
handle_error_en(s, "pthread_create");
sleep(2); /* Allow new thread to run a while */
if (argc > 1) {
if (argc > 2)
cleanup_pop_arg = atoi(argv[2]);
done = 1;
} else {
printf("Canceling thread\n");
s = pthread_cancel(thr);
if (s != 0)
handle_error_en(s, "pthread_cancel");
}
s = pthread_join(thr, &res);
if (s != 0)
handle_error_en(s, "pthread_join");
if (res == PTHREAD_CANCELED)
printf("Thread was canceled; cnt = %d\n", cnt);
else
printf("Thread terminated normally; cnt = %d\n", cnt);
exit(EXIT_SUCCESS);
}
SEE ALSO
pthread_cancel(3), pthread_cleanup_push_defer_np(3), pthread_setcancel-
state(3), pthread_testcancel(3), pthreads(7)
COLOPHON
This page is part of release 3.22 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at http://www.kernel.org/doc/man-pages/.
Linux 2008-11-24 PTHREAD_CLEANUP_PUSH(3)