是否可以将cin与cout并行使用? [英] Is there a possibility to use cin parallel to cout?

查看:105
本文介绍了是否可以将cin与cout并行使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用C ++编写一个程序,该程序将用于模拟汽车的眨眼信号。我希望它简单并且可以在控制台窗口中进行编译。

I'm trying to write a program in C++ which will be responsible for simulating blinkers in cars. I want it to be simple and to compile it in a console window.

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

Is it possible to create one thread for input which will be always active and second for output that will run simultaneously?

我想使用线程来解决这个问题,但是它并不能如我所愿。我有点难以理解线程。如果有人可以帮助我解决此问题,我将不胜感激。

I wanted to use threads to solve this but it doesn't work as I would like. I have a little trouble to understand threads. If anyone could help me to fix this I would be grateful.

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 确保线程安全的读写。最后,您应该加入分离线程。

A reference to std::atomic_int is passed to both functions for communication. std::atomic_int ensures thread-safe reads and writes. At the end you should join or detach the threads.

这篇关于是否可以将cin与cout并行使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆