jthread是否可以完全取代thread?

选择 std::thread 的场景​:

  • 需要手动控制生命周期(如延迟 join 或选择性 detach)。
  • 需要避免自动 join 的默认行为(如线程后台运行)。
  • 需要更直观地表达代码意图(如明确手动管理或所有权转移)

线程所有权转移

当需要将线程句柄传递给其他对象管理时(如线程池),std::thread 的移动语义更直接,而 std::jthread 的自动析构行为可能引入意外开销。

class ThreadPool {
public:
    void add_thread(std::thread t) {
        // 接管线程,手动管理生命周期
        threads.push_back(std::move(t));
    }
    ~ThreadPool() {
        for (auto& t : threads) {
            if (t.joinable()) t.join();
        }
    }
private:
    std::vector<std::thread> threads;
};

// 使用 std::thread 明确所有权转移
ThreadPool pool;
std::thread t([]{ /* ... */ });
pool.add_thread(std::move(t)); // 清晰表达所有权转移

// 若用 jthread,析构时自动 join 可能与线程池设计冲突

在多个条件分支中控制线程合并的时机

 

void process_result(int result) { /* ... */ }
void handle_error() { /* ... */ }

bool condition = /* 某个复杂条件 */;

// 使用 std::thread 允许手动控制 join 时机
std::thread worker([]() -> int {
    // 执行耗时计算,返回结果
    return 42;
});

// 主线程执行其他操作...

if (condition) {
    // 条件满足时,立即获取结果(需等待线程完成)
    worker.join();
    int result = /* 获取 worker 的结果 */;
    process_result(result);
} else {
    // 条件不满足时,主线程不等待,worker 继续在后台运行
    worker.detach();
    handle_error();
}

1. std::jthread 的核心改进

自动线程生命周期管理

std::thread 的问题:

  • 如果std::thread对象在析构时仍可联结(joinable()true),且未显式调用join()detach(),则程序会调用std::terminate(),导致崩溃。
  • 需要手动管理线程的合并或分离,容易出错。

std::jthread 的改进:

  • ​析构时自动调用join():若线程未分离且仍可联结,自动合并,避免崩溃。
  • 支持显式分离​:可通过detach()手动分离线程。
协作式线程中断

功能​:通过request_stop()向线程发送停止请求,线程内部可检查std::stop_token决定是否终止。

std::jthread jt([](std::stop_token st) {
    while (!st.stop_requested()) {
        std::cout << "Working..." << std::endl;
        std::this_thread::sleep_for(1s);
    }
});

// 请求线程停止
jt.request_stop();

避免手动设计线程退出标志(如atomic<bool>),简化代码 

2. std::jthread 的优势场景

需要安全自动合并线程

void func() {
    std::thread t([]{ /* ... */ });
    // 如果此处抛出异常,t 未 join/detach,程序终止!
}

需要协作式中断

// 传统方式(需要原子变量)
std::atomic<bool> stop_flag{false};
std::thread t([&stop_flag]{
    while (!stop_flag.load()) { /* ... */ }
});
stop_flag.store(true);
t.join();

// jthread 方式(无需手动管理)
std::jthread t([](std::stop_token st) {
    while (!st.stop_requested()) { /* ... */ }
});
t.request_stop();

3. std::jthread 的局限性

  • 协作式中断的代价​:std::stop_token和内部状态管理可能引入微小性能损耗。
  • 适用场景​:对性能极度敏感的场景(如高频实时系统),可能需要权衡是否使用。
无法完全替代手动控制:
  • 需要显式分离线程时​:
    std::jthread t([]{ /* ... */ });
    t.detach(); // 仍然需要显式调用
  • 无需自动合并的场景​:某些设计可能希望线程在后台运行,无需阻塞等待。

4. 何时仍需使用 std::thread

需要兼容旧版C++标准:

  • 若项目必须支持C++11/14/17,std::thread仍是唯一选择。
无需自动合并或中断功能

需要更轻量级的线程对象

  • std::jthread内部需要维护std::stop_source等状态,占用更多内存(尽管差异通常可忽略)

5. 结论:jthread vs thread

特性std::jthreadstd::thread
自动析构合并✅ 自动调用join()❌ 需手动管理,否则崩溃
协作式中断✅ 支持request_stop()❌ 需手动实现(如原子变量)
内存占用略高(包含stop_source等状态)更低
C++标准支持C++20及以上C++11及以上
适用场景需要安全生命周期管理或协作中断兼容旧标准、无需自动管理或中断

6. 补充:std::this_thread 

是 C++ 标准库 <thread> 头文件里的一个命名空间,它提供了一系列用于操作当前线程的实用函数。

std::this_thread::sleep_for

此函数可让当前线程休眠指定的时长。

#include <iostream>
#include <thread>
#include <chrono>

int main() {
    std::cout << "Sleeping for 2 seconds..." << std::endl;
    // 当前线程会休眠 2 秒,之后再继续执行后续代码。
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Woke up after 2 seconds." << std::endl;
    return 0;
}

std::this_thread::sleep_until 

#include <iostream>
#include <thread>
#include <chrono>

int main() {
    auto wake_time = std::chrono::steady_clock::now() + std::chrono::seconds(2);
    std::cout << "Sleeping until the specified time..." << std::endl;
    // 当前线程会休眠到 wake_time 这个时间点,然后再接着执行后续代码。
    std::this_thread::sleep_until(wake_time);
    std::cout << "Woke up at the specified time." << std::endl;
    return 0;
}

std::this_thread::yield 

#include <iostream>
#include <thread>

void threadFunction() {
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread: " << i << std::endl;
        // 让线程在每次循环时主动放弃 CPU 时间片,从而让其他线程有机会执行。
        std::this_thread::yield();
    }
}

int main() {
    std::thread t(threadFunction);
    for (int i = 0; i < 5; ++i) {
        std::cout << "Main: " << i << std::endl;
    }
    t.join();
    return 0;
}

std::this_thread::get_id 

返回当前线程的唯一标识符

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
}

int main() {
    std::thread t(threadFunction);
    std::cout << "Main Thread ID: " << std::this_thread::get_id() << std::endl;
    t.join();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值