Linuxシステムプログラミング54スレッド-スレッドキャンセル

pthread_cancel():スレッドをキャンセルします

pthread_setcancelstate():キャンセルを許可するかどうかを設定します

pthread_setcanceltype():キャンセル方法を非同期または延期で設定します

pthread_testcancel():キャンセルポイントを設定します

pthread_detach():スレッドデタッチ


上記のpthread_join()スレッド収集死体は、スレッドの実行が終了するのを待ってから死体を収集する必要があります。また、ターゲットスレッドが実行を終了する必要がない場合もあるので、死体を収集するにはどうすればよいですか。

pthread_cancel()+ pthread_join()


pthread_cancel():スレッドをキャンセルします

NAME
       pthread_cancel - send a cancellation request to a thread 给一个线程发送一个取消请求。

SYNOPSIS
       #include <pthread.h>

       int pthread_cancel(pthread_t thread);//取消线程, thread :需要取消的线程ID

       Compile and link with -pthread.

申請したリソースがリサイクルできないようにするため、キャンセルステータスを設定する必要があります。たとえば、キャンセルする必要のあるスレッドがファイルを開いたばかりの場合()、この時点でキャンセルすると失敗します。 close()とリソースリーク。したがって、次のステータスを次のように設定する必要があります。

キャンセルには2つの状態があります。

1キャンセル可能

1.1 异步取消
1.2 推迟取消,默认是推迟取消, 推迟到 cancel点 再响应

キャンセルポイント:POSIXで定義されているキャンセルポイントは、ブロッキングを引き起こす可能性のあるシステムコールを指します。

2キャンセルはできません

int pthread_setcancelstate(int state、int * oldstate); //キャンセルを許可するかどうかを設定します

int pthread_setcanceltype(int type、int * oldtype); //キャンセル方法を非同期または延期で設定します

NAME
       pthread_setcancelstate, pthread_setcanceltype - set cancelability state and type

SYNOPSIS
       #include <pthread.h>

// 设置 是否允许取消
       int pthread_setcancelstate(int state, int *oldstate); 

// 设置取消方式,异步 或者 推迟
       int pthread_setcanceltype(int type, int *oldtype);

       Compile and link with -pthread.

名前
pthread_testcancel-キャンセルポイントを設定します

ブロッキングを引き起こす可能性のあるシステムコールなしで関数関数に適用されます。つまり、スレッド内で、スレッドをキャンセルするためのキャンセルポイントを設定するために使用されます。

SYNOPSIS
       #include <pthread.h>

// 本函数 什么都不做,就是一个取消点
       void pthread_testcancel(void);

       Compile and link with -pthread.

pthread_detach():スレッドデタッチ

通常の状況では、Linuxリソースの原則に従います。つまり、誰がリソースを開き、誰がリソースを閉じます。誰が適用するか、誰がこの原則を解放するか。ただし、特別な状況があります。スレッドが作成され、その存続を気にしない場合は、デタッチできます
つまり、pthread_detach()です。

pthread_detach()によってデタッチされたスレッドは、pthread_join()によって収集できないことに注意してください。

NAME
       pthread_detach - detach a thread 分离一个线程

SYNOPSIS
       #include <pthread.h>

       int pthread_detach(pthread_t thread);

       Compile and link with -pthread.

おすすめ

転載: blog.csdn.net/LinuxArmbiggod/article/details/114232088