【Linux】线程控制

发布于:2025-09-07 ⋅ 阅读:(9) ⋅ 点赞:(0)

线程创建

pthread_create:

//线程要执行的函数
void* threadStart(void *args)
{
    int count = 5;
    char* str = (char*)args;
    while (count!=0)
    {
        std::cout << str << " running..., count: " << count-- << std::endl;
        sleep(1);
    }
    return 0;
}

int main()
{
    // 用于存储线程的ID
    pthread_t tid;

    int n = pthread_create(&tid, nullptr, threadStart, (void*)"new thread");

    if(n != 0)
    {
        std::cerr << "create thread error..." << std::endl;
        return 1;
    }

    std::cout << "new thread join success..." << std::endl;
    void* code = nullptr;
    // 让main线程等待new thread先执行
    n = pthread_join(tid, &code);
    
    if(n == 0)
    {
        std::cout << "main thread wait new thread success..." << std::endl;
    }
    return 0;
}

在这里插入图片描述
pthread_self():获取线程自身ID

线程终止

终止一个线程的三种方式:

  • 从线程函数 return。
  • 线程调用 pthread_exit 终止。
  • 一个线程调用 pthread_cancel 终止同一进程中的另一个线程。

pthread_exit 是线程主动终止自己,而 pthread_cancel 是终止其他线程。
使用 pthread_cancel 只是请求线程终止,而不是立即终止,所以后面还需要使用 pthread_join 来等待该线程最终完成终止并回收其资源。

//线程要执行的函数
void* threadStart(void *args)
{
    int count = 5;
    char* str = (char*)args;
    while (count!=0)
    {
        std::cout << str << " running..., count: " << count-- << std::endl;
        sleep(1);
    }
    return 0;
}

int main()
{
    // 用于存储线程的ID
    pthread_t tid;

    int n = pthread_create(&tid, nullptr, threadStart, (void*)"new thread");

    if(n != 0)
    {
        std::cerr << "create thread error..." << std::endl;
        return 1;
    }

    std::cout << "主线程: 发送取消请求..." << std::endl;
    if (pthread_cancel(tid) != 0) {
        perror("pthread_cancel");
        return 1;
    }

    std::cout << "主线程等待线程" << std::endl;
    void* code = nullptr;
    // 让main线程等待new thread先执行
    pthread_join(tid, &code);
    
    // 检查线程是否被取消
    if (code == PTHREAD_CANCELED) {
        printf("主线程: 工作线程已被成功取消。\n");
    } else {
        printf("主线程: 工作线程正常结束。\n");
    }
    return 0;
}

在这里插入图片描述
将 pthread_cancel 注释后:
在这里插入图片描述

等待线程

pthread_join:
用来等待线程结束。

int pthread_join(pthread_t thread, void **value_ptr);
参数 thread:线程ID(线程ID是一个地址)
value_ptr:它指向一个指针,后者指向线程的返回值
返回值:成功返回0;失败返回错误码

若 thread 线程通过 return 返回,那么 value_ptr 所指向的单元里存放的就是 thread 线程函数的返回值。
若 thread 线程被别的线程使用 pthread_cancel 终止,那么 value_ptr 所指向的单元里存放的就是常数 PTHREAD_ CANCELED。
若 thread 线程是自己调用 pthread_exit 终止,那么 value_ptr 所指向的单元里存放的就是 pthread_exit 参数。
若不关心线程的终止状态,可以传递 null 给 value_ptr 参数。

分离线程

用于将一个线程标记为 分离状态。核心作用是改变线程终止后的资源回收方式。当创建一个线程,且不关心执行结果,并且希望系统在线程结束后自动回收资源时 就可以将线程分离。

int pthread_detach(pthread_t thread);
参数 thread 为目标线程的 ID。
成功返回 0,失败返回非0 错误码。常见的有:EINVAL:thread不是一个可连接的线程(例如,它已经被分离,或者其属性是分离的)。ESRCH:找不到ID 为thread 的线程。
也可以使用 pthr_detach(pthread_self()) 来分离自己。

调用 pthread_detach 就是将一个可连接线程转换为分离线程。一旦被成功分离,就不能再使用 pthread_join。且线程在终止后,资源会由系统自动回收。

void* init_config(void* arg) {
    pthread_detach(pthread_self());
    load_configuration(); // 耗时操作
    config_loaded = true;
    printf("配置加载完成\n");
    return NULL;
}

// 启动初始化
pthread_create(&tid, NULL, init_config, NULL);
// 主线程可以继续启动其他服务,无需等待配置加载

网站公告

今日签到

点亮在社区的每一天
去签到