开发者

Guidelines to avoid multithreaded problems

I'm developing a game where each object has its own thread where it moves and does its operations.

I got a central object that coordinates all interaction between all objects. I've ran into multiple problems with random object just doing random things at random times and I can't reproduce these, they happen in about 1 in 100 runs. I even got a cases where impossible things happen - a field is written to in middle of the program where the only statement that writes to is at the start of the program.

What guidelines can I follow to fix this without flattering all threads by locking the central object at each pass. I don't want to flattern them because it will cause "accordion" movement. To reference accordion movement is when objects 1, 2, 3, 4, 5 need to move right and that happens (time is progressing downwards).

54321
5432 1
543 21
54 321
5 4321
 54321

EDIT: Just a clarification:

I use a framework that I think makes a thread for each object, I can't control that. All objects are called their update function in succesion and I figured out it does some of them in parallel after I got some errors that happen in multithreaded code. It might pool the threads or assign a number of objects for each thread to update but I can't be sure unless you ca开发者_如何学编程n show me how to figure this out in the scientific method.


First of all. Using a few hundred threads makes your program slower. Using thousand threads is just horrible. You should really reconsider your application design. The ThreadPool might be a better fit?

Here is a great article explaining all threading concepts: http://msdn.microsoft.com/en-us/magazine/cc163744.aspx

As I said in the comment I use a framework that automatically makes threads, I have no control over that

Well. Then you must be using the framework incorrectly. There is no way any game framework developer has made something so that it creates hundreds of threads per design.


Primarily: don't use multithreading unnecessarily, since parallelism is hard, as you are starting to discover (look at e.g. race conditions). If you think threading solves a problem, use a thread workpool to scale with the number of processors/cores, not with your problem size (number of objects).

In your specific case: isolate physics and object interactions from rendering. I suspect you can do all your object changes in one sweep (and in a single thread), and then render them, avoiding any accordionicity(!).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜