【问题标题】:Is there a possibility to use cin parallel to cout?是否有可能将 cin 与 cout 并行使用?
【发布时间】:2020-07-31 03:53:52
【问题描述】:

我正在尝试用 C++ 编写一个程序,该程序将负责模拟汽车中的闪光灯。我希望它简单并在控制台窗口中编译它。

是否可以为输入创建一个始终处于活动状态的线程,为将同时运行的输出创建第二个线程?

我想使用线程来解决这个问题,但它没有按我的意愿工作。我在理解线程方面有点麻烦。如果有人能帮我解决这个问题,我将不胜感激。

int in()
{
    int i;
    cout<<"press 1 for left blinker or 0 to turn it off: ";
    cin>>i;
    return i;
}

void leftBlinker()
{
    int i;
    cout << "<-";
    Sleep(1000/3);
    cout << "  ";
    Sleep(1000/3);

}


int main()
{
    thread t1 (in);


    if (in()==1)
    {
        for (int i=0; i<100; i++)
        {
            thread t2(leftBlinker);
            if (in()==0)
                break;
        }
    }

    system("pause");
    return 0;
}

【问题讨论】:

  • 当然有可能。你可以使用同一个终端,你可以使用两个终端,你可以使用ncurses,...许多可能的方式来实现它。
  • @ThomasSablik 举个小例子就好了。我对 C++ 还很陌生,但我现在不太了解它
  • SO 是请求教程的错误网站。尝试一下,如果您遇到特定问题,请回来,我们会尽力帮助您。您可以从两个线程开始,一个线程用于输入,一个线程用于输出。然后您可以考虑基于文本的用户界面 (TUI) 或两个终端,例如GDB 可以做到这一点。
  • 这是一个例子godbolt.org/z/GHFiqx

标签: c++ printf cin cout


【解决方案1】:

这是一个简单的示例代码:

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

int in(std::atomic_int &i) {
  while (true) {
    std::cout << "press 1 for left blinker or 0 to turn it off: ";
    int input;
    std::cin >> input;
    i = input;
  }
}

void leftBlinker(std::atomic_int &i) {
  while (true) {
    if (i) {
      std::cout << "<-" << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds{333});
      std::cout << "  " << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds{333});
    }
  }
}

int main() {
  std::atomic_int i{0};
  std::thread t1(in, std::ref(i));
  std::thread t2(leftBlinker, std::ref(i));

  t1.join();
  t2.join();
  return 0;
}

std::atomic_int 的引用被传递给两个函数进行通信。 std::atomic_int 确保线程安全的读写。最后你应该joindetach 线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多