Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 776 Bytes

062-线程.md

File metadata and controls

35 lines (26 loc) · 776 Bytes

062-线程

c++创建线程非常简单include<thread>后,直接创建线程对象并传入需要执行的方法即可

可以使用std::this_thread::get_id打印当前线程的id

下面是一个关于线程的例子

#include <iostream>
#include <thread>

static bool isFinish = false;

void doWork() {
    using namespace std::literals::chrono_literals;
    while (!isFinish) {
        std::cout << "Hello" << std::endl;
        std::this_thread::sleep_for(1s);
    }
    std::cout << "doWork: get_id " << std::this_thread::get_id() << std::endl;
}

int main() {
    std::thread thread(doWork);
    std::cin.get();
    isFinish = true;
    thread.join();
    std::cout << "main: get_id " << std::this_thread::get_id() << std::endl;
    return 0;
}