2010-04-04 55 views
1

我有一個threadMethod,它每隔0.5秒在控制檯robotMotorsStatus中顯示。但是,當我嘗試更改robotMotorsStatuschangeRobotStatus方法時,我收到一個異常。我需要把鎖放在那個程序中。可可多線程,鎖不起作用

#import "AppController.h" 

@implementation AppController 
extern char *robotMotorsStatus; 

- (IBAction)runThread:(id)sender 
{ 
[self performSelectorInBackground:@selector(threadMethod) withObject:nil]; 
} 

- (void)threadMethod 
{ 
char string_to_send[]="QFF001100\r"; //String prepared to the port sending (first inintialization) 
string_to_send[7] = robotMotorsStatus[0]; 
string_to_send[8] = robotMotorsStatus[1]; 
while(1){ 
    [theLock lock]; 
    usleep(500000); 
    NSLog (@"Robot status %s", robotMotorsStatus); 
    [theLock unlock]; 
} 

} 

- (IBAction)changeRobotStatus:(id)sender 
{ 
robotMotorsStatus[0]='1'; 
} 
+2

只要確定:您是否在某處定義了robotMotorsStatus?你有什麼異常? – Yuji 2010-04-04 22:44:12

+0

您是否閱讀過文檔? http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW1 – 2010-04-04 22:53:23

+0

什麼樣的對象是「theLock」 ; NSLock? – 2010-04-04 23:21:41

回答

0
extern char *robotMotorsStatus; 

您還沒有在任何代碼,您已經證明,設置這個指針指向任何地方。 (您是否使用了一些機器人包,將初始化這個變量爲你的SDK?如果是這樣,您可以顯示配置設置,告訴它這是初始化變量?)

string_to_send[7] = robotMotorsStatus[0]; 
string_to_send[8] = robotMotorsStatus[1]; 

如果robotMotorsStatus尚未由SDK或代碼未顯示進行初始化,則這些內存將以隨機地址訪問。如果這使你崩潰,這並不會讓我感到驚訝,如果這是你提到的但沒有提到的「例外」。

robotMotorsStatus[0]='1'; 
這裏

同潛在的問題。

NSLog (@"Robot status %s", robotMotorsStatus); 

這假定robotMotorsStatus包含至少一個字符,並且所述最後一個是一個零字節(空字符)-i.e。,即robotMotorsStatus指向C字符串。正如我已經注意到的,你沒有顯示robotMotorsStatus指向任何東西明確的,即使它指向某處,你也沒有顯示該內存的內容是C字符串。

如果數組的實際範圍內沒有空字符,則數組不包含C字符串,並試圖讀取整個C字符串,因爲將該數組傳遞給格式化程序%s會在經過數組末尾後導致崩潰。如果其他兩個訪問robotMotorsStatus不是你的崩潰,這可能是。

這裏的解決方案不僅僅是讓指針變量指向某個地方,而是讓一個有效的C字符串(包括空字符)完全位於該空間內。

順便提一下,這些問題與線程無關。