SDL2:SDL_GetMouseState() 是线程安全的吗?
SDL2: Is SDL_GetMouseState() thread-safe?
SDL_GetMouseState
函数线程安全吗?
而在SDL_GetMouseState
的例子中,使用了众所周知线程不安全的SDL_PumpEvents
。如果 SDL_GetMouseState
是线程安全的,我是否必须使用线程不安全的 SDL_PumpEvents
才能使其正常工作?
这个函数的代码是:
Uint32
SDL_GetMouseState(int *x, int *y)
{
SDL_Mouse *mouse = SDL_GetMouse();
if (x) {
*x = mouse->x;
}
if (y) {
*y = mouse->y;
}
return mouse->buttonstate;
}
而SDL_GetMouse
只是returns静态全局变量的地址。因此,它没有什么不安全的,但是没有原子性。
但是事件是单独处理的。如果你不处理事件,鼠标结构就不会更新,SDL_GetMouseState
会给你过时的值。文档明确指出您应该仅在图形线程(初始化图形系统的线程)中调用 SDL_PumpEvents
。
最坏的情况是您从 SDL_GetMouseState
读取值,而其他线程更新它。您可以读取旧值、新值,甚至是两者的混合(例如,x 来自新值,y 来自旧值)。
SDL_GetMouseState
函数线程安全吗?
而在SDL_GetMouseState
的例子中,使用了众所周知线程不安全的SDL_PumpEvents
。如果 SDL_GetMouseState
是线程安全的,我是否必须使用线程不安全的 SDL_PumpEvents
才能使其正常工作?
这个函数的代码是:
Uint32
SDL_GetMouseState(int *x, int *y)
{
SDL_Mouse *mouse = SDL_GetMouse();
if (x) {
*x = mouse->x;
}
if (y) {
*y = mouse->y;
}
return mouse->buttonstate;
}
而SDL_GetMouse
只是returns静态全局变量的地址。因此,它没有什么不安全的,但是没有原子性。
但是事件是单独处理的。如果你不处理事件,鼠标结构就不会更新,SDL_GetMouseState
会给你过时的值。文档明确指出您应该仅在图形线程(初始化图形系统的线程)中调用 SDL_PumpEvents
。
最坏的情况是您从 SDL_GetMouseState
读取值,而其他线程更新它。您可以读取旧值、新值,甚至是两者的混合(例如,x 来自新值,y 来自旧值)。