c++基础(thread)

作者: zidea | 来源:发表于2019-05-02 19:22 被阅读18次
Cplusplus-tutorial-in-hindi.jpg

线程是我们在编程中逃不开的话题,无论 java 、c# 还是 go 各种语言都有自己一套支持并发编程的支持。今天我们就来简单了解一下如何在 c++ 中创建thread以及使用thread

#include <iostream>
#include <thread>

static bool is_Finished = false;

void do_work()
{
    while (!is_Finished)
    {
        std::cout << "working...\n";
    }
}

int main(int argc, char const *argv[])
{

    std::thread worker(do_work);

    std::cin.get();
    is_Finished = true;

    worker.join();

    std::cin.get();
}

  • 引入thread库,调用std::thead创建一个 worker 线程,然后传入一个函数do_worker在此线程中运行。
  • std::cin.get() 这个函数我们一直在用,还没有解释过他的作用,作用是当程序之行到此会阻止线程执行等待用户输入回车后退出。
  • worker.join(),在线程中执行表示让主线等待worker执行完,在继续在主线程执行,有了 join 我们主线就会等待worker线程执行完毕后再继续执行。以免worker没有执行完就退出了。
  • 这里在worker线程中循环执行输出working..知道我们输入回车在退出线程。
void do_work()
{
    using namespace std::literals::chrono_literals;
    while (!is_Finished)
    {
        std::cout << "working...\n";
        std::this_thread::sleep_for(1s);
    }
}
std::this_thread::sleep_for(1s);

可以让thread休眠 1 秒钟

g++ -std=c++14 thread1.cpp -o thread1
void do_work()
{
    using namespace std::literals::chrono_literals;
    std::cout << "started thread id = " << std::this_thread::get_id() << std::endl;
    while (!is_Finished)
    {
        std::cout << "working...\n";
        std::this_thread::sleep_for(1s);
    }
}
std::cout << "started thread id = " << std::this_thread::get_id() << std::endl;
```
输出 thread 的 id。

相关文章

  • c++基础(thread)

    线程是我们在编程中逃不开的话题,无论 java 、c# 还是 go 各种语言都有自己一套支持并发编程的支持。今天我...

  • 初识c++多线程

    主要参考以下两篇博客c++多线程 thread类c++实现线程池当一个thread被创建以后要么join等待线程执...

  • 翻译:Cancelling a thread using pth

    Stack overflow地址:c++ - Cancelling a thread using pthread_...

  • C++ concurrency[1]

    结合C++ concurrency in action Passing data to a thread by v...

  • 翻译:How to name a thread in Linux

    Stack overflow地址:c++ - How to name a thread in Linux? - S...

  • error: attempt to use a deleted

    error: attempt to use a deleted function 使用c++ thread 的时...

  • { 1 }CPP_线程管理的基础

    一,启动线程 1. 使用C++线程库启动线程,即为构造std::thread对象: std::thread构造方法...

  • Thread基础

    记录Java Thread的基础点。 线程的实现 线程的定义有两种方式 继承Thread类 实现Runnable接...

  • 多线程

    _thread模块 基础知识 开启一个新线程 _thread.start_new_thread(functio...

  • posix thread封装

    在看阅读RCF源码时,学习了一下posix thread在c++下的封装。 posix_thread.hpp th...

网友评论

    本文标题:c++基础(thread)

    本文链接:https://www.haomeiwen.com/subject/batonqtx.html