【发布时间】: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()在mainworks fine。 -
“不工作”是什么意思?在不了解多执行线程、线程同步和锁定或核心 C++ 基础知识的情况下,所有试图追逐和捕捉难以捉摸的无锁原子独角兽仙子的尝试,但仅仅是因为阅读了谷歌搜索结果,最终会什么都抓不到。这具有基于谷歌搜索结果学习多线程编程的所有指纹,而不是基于教科书的资源。
标签: c++ multithreading