[英]How can I print two functions at the same time in C?
我在控制台應用程序上用C做游戲,我需要在用戶同時玩游戲時打印計時器,我不知道如何編程那么好,實際上我只是開始使用這個編譯器所以我不知道很多多線程和東西,但這是我得到的,這是兩個函數的例子,第一個是“計時器”,第二個只是一些問題, 我的疑問是,如果我可以運行這兩個函數在同時,我可以打印計時器,而我可以在不中斷控制台的情況下回答這兩個問題。
例:
#include <windows.h>
#include <stdio.h>
#include <time.h>
DWORD WINAPI Timer(int limit)
{
int secs = 1;
time_t unix;
struct tm * timeinfo;
time(&unix);
timeinfo = localtime(&unix);
int t1 = timeinfo->tm_sec;
int t2 = timeinfo->tm_sec;
int i = 0;
while(1 == 1)
{
time(&unix);
timeinfo = localtime(&unix);
if((t1 + i) == timeinfo->tm_sec)
{
system("cls");
printf("time left %d seconds\n", timeinfo->tm_sec - t2 - limit);
i++;
}
if(timeinfo->tm_sec >= (t1 + limit))
{
break;
printf("Your time its done");
}
}
return 0;
}
DWORD WINAPI Questionary()
{
puts("testing\n\n");
int age, height;
printf("Please write your age: ");
scanf("%d", &age);
printf("Please write your height: ");
scanf("%d", &height);
printf("\n\nThe numbers written are %d y %d", age, height);
return NULL;
}
int main()
{
int i, limit;
HANDLE tempo;
HANDLE questions;
DWORD ThreadId;
printf("\nHow much time would you like for your timer countdown? ");
scanf("%d", &limit);
//Funcion Handle
questions= CreateThread(NULL,0,Questionary,1,0,&ThreadId);
WaitForSingleObject(preguntas,INFINITE);
tempo= CreateThread(NULL,0,Timer(limit),1,0,&ThreadId);
WaitForSingleObject(tiempofinal,limit*40);
return 0;
}
您可以打印問題,而不是等待阻塞調用(如scanf
)中的答案,而是在輪詢新輸入時循環,並使用ANSI轉義碼在另一個位置打印時間。
像下面的偽代碼:
print(question)
while (current_time < timer_end)
{
if (have_input())
break
save_current_cursor_position()
move_cursor_position(x, y)
print(timer)
restore_saved_cursor_position()
very_short_sleep()
}
您想要的線程,無法通過面向行的函數來完成,多線程控制台讀/寫操作需要像ncurses這樣的東西。
Joachim Pileborg寫的是你最好的機會,限制是你等待輸入時你的時鍾不能滴答作響。如果你每1秒輪詢一次,寫下時間然后等待答案,大多數人都不會能夠在1秒內回復,所以每10秒也許是最明智的。
在每秒仍然輪詢的情況下每隔一秒顯示時間滴答的另一種方法是將該秒的輸入保存在累積緩沖區上,並在下一次輸入輪詢時在屏幕上重寫它,除了時間滴答。 這確實存在在循環交替時丟失一些輸入並且編碼更復雜的危險。
這種情況下,圖形界面更適合您的需求。
Y seria buena idea que traduzcasalingléstusnombres de variables para ayudar aunamásrápidacomprensióndelcontenido de tu programa,ya que es lo que entiende lamayoríacapá。
據我所知,無法同時從不同的線程寫入控制台。 它看起來兩個線程正在同時寫入,實際上其中一個是一次寫入(其中一個是抓住控制台寫的)。 通過這種方式,兩個線程同時運行,它沒有意義。
我認為你可以在一個線程中解決你的問題,但這並不是一件好事。 但我認為你可以gui組件,從兩個不同的線程,你可以設置這個組件的字段,這滿足您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.