我有一个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