Cocoa多线程,锁不起作用

时间:2010-04-04 22:37:22

标签: cocoa multithreading

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

1 个答案:

答案 0 :(得分: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字符串 - 包括空字符 - 完全在该空间内。

顺便说一句,这些问题与线程无关。