• Log in
Anwen  Share and Create
  • Book
  • Movies
  • Music
  • SF
  • Goodlink
  • Asks
  • Eyeopen
  • Create

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

Sharer: 阅微堂 December 23, 2019 at 11:00 pm
Link Share :https://zhiqiang.org/coding/std-thread.html - via RSS

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(即使这个新建线程的任务已经执行完毕!)。

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

分离线程则是新创建的线程和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的析构函数里设置了如果线程既没有合并也没有分离,程序就会自动退出!

~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;
}
作者暂无likerid, 赞赏暂由本网站代持,当作者有likerid后会全部转账给作者(我们会尽力而为)。

Tips: Until now, everytime you want to store your article, we will help you store it in Filecoin network. In the future, you can store it in Filecoin network using your own filecoin.


Support author:
Author's Filecoin address:
Or you can use Likecoin to support author:
tags:编程 C++ C++标准库 std::thread

0 0

2012-2018 Anwen All of our posts are default licensed under CC BY 4.0 About Help Changelog Telegram
Today Quote: 一切拥有权力的人都有滥用权力为自己谋求私利的倾向;任何专制的国家的教育目的都是在极力降低国民的心智。 -- 孟德斯鸠