开发者

How to make sure a thread gets the most recent variables modified by another thread?

Ok, so I am making a 2D game, and all the map is represented in a 2D Array. I have this huge methods that modifie开发者_JAVA百科s the map based on what is already in the map. So after a while implementing features, the FPS is lowering, so I decided to try to use multiple threads to make it faster ( Good thing, no? ).

I made 3 Threads to do the work, one that paints and handles Events, one that updates the base part of the map and the other updates another set of variables. The problem is, it paints but it does not update when I start all 3 Threads. It does update when I call the methods from the painting thread. I tested the first updating thread by adding "System.exit(0);" at the run, and it did not started when it otherwise would start. I also tried to manually change a tile of the map directly in the run method of the Updating thread, but it did nothing. So I concluded the run is executed, and the variables are modified. So I thought that maybe the variables used by the painter aren't the updated ones.

All the variables are in a seperated class and are static ( Was that right? ) and were accessed by an object, but then I changed it to 'Direct' Access ( IDE Suggestion ) with the code "nameOfTheClass.variableName"

Almost forgot to mention, the Events ( In the class with the paint() method ) modifies the Map, and this part does work.

I don't know what to do, anyone got an idea?


You need to mark the offending variable as volatile, which will prevent the compiler from caching a copy in a local variable, instead reading/writing the actual value each time.


I believe the problem is a race condition instead. The variable modification may be 'delayed' (by a few hundred nanoseconds?) as other accesses go through, but it will still happen, eventually. In this case, I don't think volatile or anything like that will make a difference, since the ordering of thread syncs should not be important. If it is, you have bigger things to worry about. Also, I think your terminology might be a bit messed up --I can't really understand the threading issue in relation to your code.

If you need hard synchronisation, you can establish resource 'fences' (synchronization blocks) and keep your resource accesses within these fences, so that race conditions cannot occur. You establish transactions by nature of the fact that nothing can get into the fence while you are operating on these variables.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜