开发者

What is the best practice for sharing objects between threads for a real time game

I want to create a real time game. The game will have a model which will be updated periodically...

- (void) timerTicks {
    [model iterate];
}

Like all game开发者_开发百科s, I will revive user input events, touches. In response I will need to update the model....

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [model updateVariableInModel];
}

So there are two threads:

  1. From a timer. Frequently iterates the model
  2. From the UI thread. Updates the the model based on user input

Both threads will be sharing variables in the model.

What is the best practice for sharing the objects between the threads and avoiding multi threading issues?


Lock the objects that need to be shared across the thread by using the @synchronized keyword.

An easy way to lock all objects is like this:

 -(void) iterate
 {
     @synchronized(self)
     {
         // this is now thread safe
     }         
 }

 -(void) updateVariableInModel
 {
     @synchronized(self)
     {
         // use the variable as pleased, don't worry about concurrent modification
     }
 }

For more info on threading in objective-c, please go here

Also note that you must lock the same object both times, or else the lock itself is useless.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜