2010-12-01 94 views
0

我想创建一个实时游戏。游戏将有一个模型,将定期更新... ...实时游戏线程之间共享对象的最佳做法是什么

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

像所有的游戏,我会恢复用户输入事件,触及。作为回应,我将需要更新模型....

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

所以有两个线程:

  1. 从一个计时器。经常迭代模型
  2. 来自UI线程。根据用户输入更新模型

两个线程将在模型中共享变量。

在线程之间共享对象并避免多线程问题的最佳实践是什么?

+0

`itterate`是什么意思?我认为你的意思是`iterate`。 – 2010-12-01 21:01:06

+0

是的,谢谢。 – Robert 2010-12-01 21:02:56

回答

1

使用@synchronized关键字锁定需要在线程中共享的对象。

一个简单的方法来锁定所有的对象是这样的:

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

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

有关在Objective-C线程的详细信息,请访问here

另外请注意,您必须两次锁定同一目标,否则锁本身就没用了。

相关问题