CLion19 threads

Requirements:

worker线程打印Working...到console,待输入enter之后就停止打印并输出Finished.到console,但是不结束程序;再次输入enter再结束

Do

  • doWork作为function pointer传入main之后,主线程新开的worker线程doWork
  • s_finished作为flag检测是否有输入enter => cin.gets_finished设置前
  • work.join: 主线程等待worker执行完成

Achtung !

std::cin.get(); s_finished = true;应该在worker.join();之前:才能改变s_finished这个flag;如果在后面,那么flag无法改变状态,worker线程就永远不会结束

Answer

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

bool s_finished = false;

void doWork() {
    while (!s_finished){
        std::cout << "Working ... \n";
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main() {
    std::thread worker(doWork);

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

    worker.join();

    std::cout << "Finished." << std::endl;
    std::cin.get();
}

Wrong Answer

int main() {
    std::thread worker(doWork);

    worker.join(); // wrong, should be put later

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

    std::cout << "Finished." << std::endl;
    std::cin.get();
}

分别的debug效果:左边能改变flag终止,右边无法结束


debug

Print thread id

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

bool s_finished = false;

void doWork() {
    std::cout << "Started thread id= " << std::this_thread::get_id() << std::endl;
    while (!s_finished){
        std::cout << "Working ... \n";
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main() {
    std::thread worker(doWork);

    std::cin.get();
    s_finished = true;
    worker.join();

    std::cout << "Finished." << std::endl;
    std::cout << "Started thread id= " << std::this_thread::get_id() << std::endl;

    std::cin.get();

推荐阅读更多精彩内容