中断/终止线程执行

#include <memory.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <thread>


int main(int argc, char** argv)
{
    static pthread_t tid1{};
    pthread_create(&tid1, nullptr, [](void* arg) -> void*
        {
            pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); //设置立即取消 
            // pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); // 默认是开启的

            // 使用非标准布局struct,会导致崩溃
            //Testdestruct t;

            struct sigaction act = {};

            sigaddset(&act.sa_mask, SIGURG);
            static int i = 0;
            act.sa_handler = [](int sig)
            {
                printf("recv signal %d, current tid=%d, i = %d\n", sig, gettid(), i);
                // 退出线程
                pthread_cancel(tid1);
            };

            sigaction(SIGURG, &act, NULL);

            printf("current tid=%d\n", gettid());

            for (;;)
            {
                ++i;
            }
            return nullptr;
        },
        nullptr);


    std::this_thread::sleep_for(std::chrono::seconds(1));

    std::thread(
        [&]
        {
            // 发送信号中断线程
            pthread_kill(tid1, SIGURG);
        })
        .detach();

    pthread_join(tid1, nullptr);
    printf("exit\n");

    return 0;
}


推荐用 timer_create()/timer_settime()来触发中断