【发布时间】:2016-03-14 00:48:15
【问题描述】:
我正在开发一款游戏,其中有一个单词落在屏幕底部,并且用户在该单词到达底部之前输入了该单词。因此,您将能够在单词下降时输入输入。现在我有一个等待 5 秒的计时器,打印单词,再次运行计时器,清除屏幕,然后将单词打印 10 个单位。
int main()
{
for (int i = 0; i < 6; i++)
{
movexy(x, y);
cout << "hello\n";
y = y + 10;
wordTimer();
}
}
我知道的很基本。这就是为什么我认为多线程是一个好主意,这样我就可以在我仍然在底部输入输入的同时让单词落下。到目前为止,这是我的尝试:
vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.push_back(std::thread(task1, "hello\n"));
threads.push_back(std::thread(wordTimer));
}
for (auto& thread : threads) {
thread.join();
}
但是,这只会在屏幕上打印 4 次 hello,然后打印 55,然后再次打印 hello,然后再倒计时 3 次。那么有关如何正确执行此操作的任何建议?我已经研究过了。我检查的一些链接没有帮助:
C++11 Multithreading: Display to console
Render Buffer on Screen in Windows
Threading console application in c++
Create new console from console app? C++
https://msdn.microsoft.com/en-us/library/975t8ks0.aspx?f=255&MSPPError=-2147217396
http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
编辑: 这里是 wordTimer()
int wordTimer()
{
_timeb start_time;
_timeb current_time;
_ftime_s(&start_time);
int i = 5;
for (; i > 0; i--)
{
cout << i << endl;
current_time = start_time;
while (elapsed_ms(&start_time, ¤t_time) < 1000)
{
_ftime_s(¤t_time);
}
start_time = current_time;
}
cout << " 5 seconds have passed." << endl;
return 0;
}
wordTimer() 也需要这个
unsigned int elapsed_ms(_timeb* start, _timeb* end)
{
return (end->millitm - start->millitm) + 1000 * (end->time - start->time);
}
和任务1
void task1(string msg)
{
movexy(x, y);
cout << msg;
y = y + 10;
}
and void movexy(int x, int y)
void movexy(int column, int line)
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE),
coord
);
}
【问题讨论】:
-
什么是
task1?那是wordtimer?请发布一个包含您的问题的代码示例,我们可以自己编译。 -
@Marinos_K 抱歉 >.
-
" 这只会在屏幕上打印 hello 4 次,然后打印 55,然后再次打印 hello,然后再倒计时 3 次。" - 你期待它做什么?
-
@immibis 不,我希望它先打印 hello 然后倒计时,打印 hello 然后倒计时,等等。我希望它以该顺序运行这些线程,同时让另一个线程连续运行以检查输入是否为等于您输入的字符串。
-
@immibis 感谢您的快速回复!
标签: c++ multithreading timer io