在 Linux 上使用 c++ 中的键退出无限循环



我有一个无限循环,如果我按下任何键,应该结束。该程序在Linux中运行。我偶然发现了一个函数 这是我的一些代码:

int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}

所以我知道我可以通过在终端中使用 Ctrl + C 来终止该过程,但它似乎会中断写入过程,因此数据不会在过程中完全写入。我读到我需要使用 ncurses 库中的函数,但我不太明白。

有人可以帮我吗?谢谢!

您可以声明一个atomic_bool并将主循环移动到另一个线程。现在你可以用一个简单的cin等待,一旦用户按下任何键,你就退出循环。

std::atomic_boolean stop = false;
void loop() {
    while(!stop)
    {
        ParseData(); // your loop body here
    }
}
int main() {
    std::thread t(loop); // Separate thread for loop.
    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    std::cin.get();
    // Set the atomic boolean to true. The loop thread will exit from 
    // loop and terminate.
    stop = true;
    t.join();
    return 0;
}

为什么你需要一个键来退出一个没有完成写入文件的程序,即使你在按键时循环退出,如果没有完成,它也会中断文件写入。

为什么在数据完成写入文件时退出循环,如下所示:

isFinished = false;      
While(!isFinished ){
    ParseData(); //writing data to a text file
   //after data finsihes
   isFinished = false;
  }
<</div> div class="one_answers">

线程.cpp

#include <atomic>
#include <iostream>
#include <thread>
std::atomic<bool> dataReady(false);
void waitingForWork(){
    std::cout << "Waiting... " << std::endl;
    while ( !dataReady.load() ){ 
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    std::cout << "Work done " << std::endl;
}
int main(){
  std::cout << std::endl;
  std::thread t1(waitingForWork);
  std::cout << "Press Enter to Exit" << std::endl;
  std::cin.get();
  dataReady= true; 
  t1.join();
  std::cout << "nn";
}

g++ -o thread thread.cpp -std=c++11 -pthread

C方式实际上(包括conio.h(:

char key;
while (1)
{
    key = _getch();
    // P to exit
    if (key == 'p' || key == 'P')
    {
        writer.close();
        exit(1);
    }
}

最新更新