指定されたスレッドを Linux で中断させる方法は?

Linuxにおいて、指定したスレッドを停止させるためには以下の方法を使用できる。

  1. pthread_kill()
#include <signal.h>

int pthread_kill(pthread_t thread, int sig);

threadパラメータは一時停止するスレッドの識別子で、pthread_self()関数を用いて現在スレッドの識別子を取得できます。sigパラメータは送信するシグナルで、シグナルSIGSTOPを使用してスレッドを一時停止できます。サンプルコードは次の通りです:

#include <pthread.h>
#include <signal.h>

void* myThreadFunc(void* arg) {
    // 线程的具体逻辑
    // ...
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, myThreadFunc, NULL);
    // 挂起线程
    pthread_kill(tid, SIGSTOP);
    return 0;
}
  1. pthread_サスペンド()
#include <pthread.h>

int pthread_suspend(pthread_t thread);

示例代码如下:

#include <pthread.h>

void* myThreadFunc(void* arg) {
    // 线程的具体逻辑
    // ...
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, myThreadFunc, NULL);
    // 挂起线程
    pthread_suspend(tid);
    return 0;
}

なお、Linuxではスレッドの停止と再開は、関数ではなく信号を使って行われるのが一般的です。

bannerAds