我有一個threadMethod
,它每隔0.5秒在控制檯robotMotorsStatus
中顯示。但是,當我嘗試更改robotMotorsStatus
changeRobotStatus
方法時,我收到一個異常。我需要把鎖放在那個程序中。可可多線程,鎖不起作用
#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';
}
只要確定:您是否在某處定義了robotMotorsStatus?你有什麼異常? – Yuji 2010-04-04 22:44:12
您是否閱讀過文檔? 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
什麼樣的對象是「theLock」 ; NSLock? – 2010-04-04 23:21:41