【问题标题】:End thread from parent main vs. another thread从父主线程与另一个线程结束线程
【发布时间】:2022-08-06 03:17:58
【问题描述】:

我是 C++ 新手,正在尝试运行两个线程:

i) 一直循环的线程,直到一个原子布尔值被翻转。

ii) 从键盘轮询输入并翻转原子布尔值的线程。

我似乎无法让 std::cin.get() 对输入做出反应,除非它被分配了自己的线程(如下所示)。为什么?那么它不会从父主线程中设置吗?

#include <iostream>
#include <iomanip> // To set decimal places.
#include <thread> //std::thread
#include <atomic> //for atomic boolean shared between threads.
#include <math.h>

#define USE_MATH_DEFINES //For PI

std::atomic<bool> keepRunning(false); //set to false to avoid compiler optimising away.

void loop(){
    int t = 1;
    while(!keepRunning.load(std::memory_order_acquire)) //lower cost than directly polling atomic bool?
    {
        //Write sine wave output to console.
        std::cout << std::setprecision(3) << sin(M_PI * 2 * t/100) << std::endl;
        (t<101)? t++ : t = 1;
    }
}

//This works, as opposed to stopping in main.
void countSafe(){
    int j = 1;
    while (j<1E7)
    {
        j++;
    }
    keepRunning.store(true, std::memory_order_release); //ends the loop thread.     
}



int main(){
    
    std::thread first (loop); //start the loop thread
    std::thread second (countSafe); //start the countSafe thread. Without this it doesn\'t work.

    //Why does polling for std::cin.get() here not work?

    //std::cin.get(); //wait for key press. puts in buffer..?
    //keepRunning.store(true, std::memory_order_release); //Set stop to true.

    second.join(); //pause to join.
    first.join(); //pause to join
    
    

    return 0;
}
  • 我不确定你在说什么。 std::cin.get()main works fine
  • “不工作”是什么意思?在不了解多执行线程、线程同步和锁定或核心 C++ 基础知识的情况下,所有试图追逐和捕捉难以捉摸的无锁原子独角兽仙子的尝试,但仅仅是因为阅读了谷歌搜索结果,最终会什么都抓不到。这具有基于谷歌搜索结果学习多线程编程的所有指纹,而不是基于教科书的资源。

标签: c++ multithreading


【解决方案1】:

我不太确定您的问题是什么,但使用 cin.get() 可能是其中的一部分。让我们用这段代码简化一下:

#include <iostream>

using namespace std;


int main(int, char **) {
    cout << "Type something: ";
    cin.get();
    cout << "Done.\n";
}

尝试该代码并运行它。然后键入单个字符。代码可能无法识别它。您可以输入所有您想要的内容,直到您按下回车键。

这很复杂,但是除非您玩其他游戏,否则您的程序直到您按回车时才真正接收字符。就像我说的,这很复杂。

Windows 上的行为可能不同,但这是 Mac 和 Linux 上的行为。

那么它“不起作用”是因为您尝试输入空格但您真的需要使用 Return 吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多