2
我正在創建一個名爲「Point and Fame」的遊戲,它基於數字的組合來猜測編譯器將其隨機抽取出來,我必須添加一個將在遊戲運行的同時打印的計時器,已經明白我需要創建一個多線程進程,我不知道該怎麼做。如何創建一個與C中的遊戲同時工作的計時器?
如果還有另一種方法把定時器放在遊戲中,或者讓循環同時運行會對我有很大的幫助。
我正在創建一個名爲「Point and Fame」的遊戲,它基於數字的組合來猜測編譯器將其隨機抽取出來,我必須添加一個將在遊戲運行的同時打印的計時器,已經明白我需要創建一個多線程進程,我不知道該怎麼做。如何創建一個與C中的遊戲同時工作的計時器?
如果還有另一種方法把定時器放在遊戲中,或者讓循環同時運行會對我有很大的幫助。
我讀這篇文章之前,不知道這是否會幫助,但只檢查this
#include <stdio.h>
#include <pthread.h>
/* This is our thread function. It is like main(), but for a thread */
void *threadFunc(void *arg)
{
char *str;
int i = 0;
str=(char*)arg;
while(i < 10)
{
usleep(1);
printf("threadFunc says: %s\n",str);
++i;
}
return NULL;
}
int main(void)
{
pthread_t pth; // this is our thread identifier
int i = 0;
/* Create worker thread */
pthread_create(&pth,NULL,threadFunc,"processing...");
/* wait for our thread to finish before continuing */
pthread_join(pth, NULL /* void ** return value could go here */);
while(i < 10)
{
usleep(1);
printf("main() is running...\n");
++i;
}
return 0;
}
這取決於你的工作是什麼平臺上。 –
如果你不想線程,每次你在遊戲循環結束時檢查系統定時器。如果足夠增加,請更新您的計時器值並重新打印。只要你不在代碼的任何地方「阻塞」(比如等待輸入)就可以工作。 –
你不一定需要去多線程。如果你能讓你的操作系統以足夠的速度給你一個普通的定時器回調,你可以完成與該速率相關的所有事情。不要只是在遇到問題時拋出線程。 – JustJeff