【发布时间】:2019-11-15 10:03:15
【问题描述】:
所以我是一个编程新手,想写一个2048年倒计时的游戏。当时间到了,定时器应该使用pthread_kill()来结束runTheGame(),这是玩游戏的函数。
我搜索了互联网,他们告诉我使用 pthread_kill(functionName, SIGQUIT)。你知道我的故事的其余部分:VS 不知道 SIGQUIT。
我知道 VS 不支持 pthread,所以我按照一些指南让它工作。除了将 .h 放入路径之外,我发现我必须确保源以 .c 而不是 .cpp 结尾,否则编译器会说 pthread_create() 的第三个参数有一些错误。
此外,我在源代码的开头写了“#pragma comment(lib,"pthreadVC2.lib")”。如果我不这样做,就会出现其他问题。
在所有这些准备之后,我成功运行了一个程序,该程序计算 _getch() 捕获的字符数,同时在另一个线程中同时计算经过的秒数。
所有这些信息都是为了证明我已经(部分)正确地将 pthread.h 安装到了 VS 中。我以为我的 pthread 会很好地工作,天知道为什么它现在出了点问题。
#pragma comment(lib,"pthreadVC2.lib")
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<time.h>
pthread_t runTheGame;
//***unneccessary code is hidden***
void timerTick()//function for doing countdown
{
for (;;)
{
restTime--;
if (restTime <= 0)
{
pthread_kill(runTheGame,SIGQUIT);//VS doesn't recognize the SIGQUIT
if (score >= goalOfLevel[arcadeLevel - 1])
{
//code is not written yet
}
}
_sleep(1000);
}
}
//***unneccessary code is hidden***
void gameRunning()//Real game loop. Run by pthread_create().
{
//***unneccessary code is hidden***
}
//***unneccessary code is hidden***
void game(int arcade)//function for initializing the game
{
arcadeLevel = arcade;
boardRange = 4;
oversize = 2048;
score = 0;
revive = 0;
doubleScoreOrNot = 1;
if (arcadeLevel > 0)
{
restTime = timeOfLevel[arcadeLevel - 1];
if (passivePower[0] == 1)
{
boardRange++;
}
if (passivePower[1] == 1)
{
revive = 1;
}
if (passivePower[3] == 1)
{
oversize = 1024;
}
if (passivePower[4] == 1)
{
score=goalOfLevel[arcadeLevel-1]/10;
}
if (passivePower[5] == 1)
{
restTime += restTime /20*3;
}
if (passivePower[7] == 1)
{
boardRange--;
doubleScoreOrNot = 2;
}
}
pthread_create(&runTheGame, NULL, gameRunning, NULL);//after all these initialization, real game starts here
}
感谢您的帮助。
【问题讨论】:
-
SIGQUIT是特定于 POSIX 的信号,它不存在于 Windows。您确定您的 POSIX 线程库定义了它吗?如果有,在哪个头文件中? -
其实.h中没有定义。但实际上整个 pthread.h 并不是 Windows 的东西。通过做所有这些准备工作,我认为我已经为我的 VS 提供了全部内容。
-
参见例如this
signalfunction reference 获取 Windows 上支持的信号列表。以及为这些信号包含哪个头文件。 -
你没有
#include <signal.h>。它不存在于您的实现中吗? -
您是想编写一个可移植的程序,还是只能在 Windows 上运行?如果您只针对 Windows,那么您不需要可移植性,我建议您改用 WINAPI 函数(例如
CreateThread)。
标签: c visual-studio-2017 pthreads signals