是否有可能将 cin 与 cout 并行使用?

Is there a possibility to use cin parallel to cout?

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

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

我想用线程来解决这个问题,但它并没有像我希望的那样工作。我在理解线程方面有点困难。如果有人能帮我解决这个问题,我将不胜感激。

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;
}

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

#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 线程。