5

C++ 标准库 std::thread 的用法和实现

 3 years ago
source link: https://zhiqiang.org/coding/std-thread.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++ 标准库 std::thread 的用法和实现

作者: 张志强

, 发表于 2019-12-24

, 共 1092 字 , 共阅读 1087 次

std::thread是 C++ 11 新引入的标准线程库。在同样是 C++ 11 新引入的 lambda 函数的辅助下,std::thread用起来特别方便:

int a = 1;
std::thread thread([a](int b) {
    return a + b;
}, 2);

它唯一有点令人疑惑的地方在于其提供的join()detach()函数,字面上的意思是前者合并线程,后者分离线程。无论是合并还是分离,都会导致std::thread::joinable()返回false,而在此之前为true(即使这个新建线程的任务已经执行完毕!)。

合并线程join()的含义比较清楚,就是绑定的线程合并到当前线程执行,当前线程被堵塞,直到被合并的线程执行完毕。

分离线程detach()则是将新创建的线程和std::thread对象分离,创建的线程独立运行。std::thread将不再持有该线程。有人可能觉得这种毫无意义,但理论上还是有的,比如分离后,我们就可以析构std::thread对象,而不会影响创建的线程(创建的线程会继续运行)。

int a = 1;

{
    std::thread thread1([a](int b) {
        return a + b;
    }, 1);

    thread1.detach();
}

{
    std::thread thread2([a](int b) {
        return a + b;
    }, 2);
}

以上面代码为例,thread1不会出错,但thread2会导致程序退出。原因是std::thread的析构函数里设置了如果线程既没有合并也没有分离,程序就会自动退出!

std::thread::~thread() {
    if (joinable()) std::terminate();
}

其源代码位于https://gcc.gnu.org/onlinedocs/gcc-7.5.0/libstdc++/api/a00158_source.html,实现非常简单,是基于pthread的封装,其内容只有线程 ID :

class thread {
public:
    typedef __gthread_t native_handle_type;
    class id {
        native_handle_type   _M_thread;
    };

private:
    id _M_id;
}

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK