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

问题描述 投票:0回答:1

我正在尝试用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;
}

c++ printf cin cout
1个回答
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线程。

© www.soinside.com 2019 - 2024. All rights reserved.