问题
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;
}
回答1:
Here is a simple example code:
#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;
}
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.
来源:https://stackoverflow.com/questions/61275142/is-there-a-possibility-to-use-cin-parallel-to-cout