gpt4 book ai didi

c++ - 是否可以将cin与cout并行使用?

转载 作者:行者123 更新时间:2023-12-02 10:18:05 24 4
gpt4 key购买 nike

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

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

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

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

关于c++ - 是否可以将cin与cout并行使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com