简体   繁体   English

使用SDL / C ++处理事件的最佳方法是什么

[英]What is the best way to handle event with SDL/C++

I am using SDL for the view parts of my game project. 我正在使用SDL作为游戏项目的视图部分。 And I want to handle key press events without interrupting the main thread. 我想在不中断主线程的情况下处理按键事件。 So I decided to run an infinite loop in another view thread to catch any events and inform the main thread. 所以我决定在另一个视图线程中运行一个无限循环来捕获任何事件并通知主线程。 However, I am not sure that this is the best since this may cause a workload and decrease the system performace? 但是,我不确定这是否是最好的,因为这可能会导致工作负载并降低系统性能? Is there any better way to do this kind of things? 有没有更好的方法来做这种事情? Thanks. 谢谢。

Don't bother with another thread. 不要打扰另一个线程。 What's the point? 重点是什么?

What does your main thread do? 你的主线程做什么? I imagine something like this: 我想象这样的事情:

  1. Update Logic 更新逻辑
  2. Render 给予
  3. Goto 1 转到1

If you receive input after (or during) the update cycle then you have to wait till the next update cycle before you'll see the effects. 如果在更新周期之后(或期间)收到输入,则必须等到下一个更新周期才能看到效果。 The same is true during rendering. 渲染过程中也是如此。 You might as well just check for input before the update cycle and do it all singlethreaded. 您也可以在更新周期之前检查输入并完成所有单线程。

  1. Input 输入
  2. Update Logic 更新逻辑
  3. Render 给予
  4. Goto 1 转到1

Multithreading gains nothing here and just increases complexity. 多线程在这里没有任何好处,只会增加复杂性。

For some added reading, check out Christer Ericson's blog post about input latency (he's the director of technology for the team that makes God of War). 有关一些补充阅读,请查看Christer Ericson关于输入延迟的博客文章 (他是制造战争之神的团队的技术总监)。

And I want to handle key press events without interrupting the main thread. 我想在不中断主线程的情况下处理按键事件。

SDL is not inherently an interrupt or event driven framework. SDL本质上不是一个中断或事件驱动的框架。 IO occurs by reading events off of the event queue by calling SDL_WaitEvent or SDL_PollEvent . 通过调用SDL_WaitEventSDL_PollEvent从事件队列中读取事件来进行IO。 This must occur in the " main " thread, the one that called SDL_SetVideoMode . 这必须发生在“ ”线程中,即调用SDL_SetVideoMode线程。

That's not to say you cannot use multiple threads, and there's good justification for doing so, for instance, it can simplify network communication if it doesn't have to rely on the SDL event loop. 这并不是说你不能使用多个线程,并且有充分的理由这样做,例如,如果它不必依赖于SDL事件循环,它可以简化网络通信。 If you want the simulation to occur in a separate thread, then it can pass information back and forth through synchronized shared objects. 如果您希望模拟在单独的线程中进行,那么它可以通过同步的共享对象来回传递信息。 In particular, you can always put events into the SDL event queue safely from any thread. 特别是,您始终可以从任何线程安全地将事件放入SDL事件队列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM