2010-12-01 55 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

另外請注意,您必須兩次鎖定同一目標,否則鎖本身就沒用了。

相關問題