Cocoa 如果有多个线程,锁不起作用
我有一个threadMethod,它每0.5秒在控制台robotMotorsStatus中显示一次。但当我试图在changeRobotStatus方法中更改robotMotorsStatus时,我收到一个异常。我需要把锁放在那个程序里Cocoa 如果有多个线程,锁不起作用,cocoa,multithreading,Cocoa,Multithreading,我有一个threadMethod,它每0.5秒在控制台robotMotorsStatus中显示一次。但当我试图在changeRobotStatus方法中更改robotMotorsStatus时,我收到一个异常。我需要把锁放在那个程序里 #import "AppController.h" @implementation AppController extern char *robotMotorsStatus; - (IBAction)runThread:(id)sender { [self
#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';
}
在所显示的任何代码中,都没有将此指针设置为指向任何位置。您是否正在为一些机器人软件包使用SDK,以便为您初始化此变量?如果是,您能否显示配置设置,告诉它这是要初始化的变量
如果robotMotorsStatus尚未通过SDK或未显示的代码进行初始化,则它们正在以随机地址访问内存。如果这会让你崩溃,如果这是你提到但没有提到的“例外”,我也不会感到惊讶
同样的潜在问题
这假设robotMotorsStatus至少包含一个字符,最后一个字符是零字节的空字符,即robotMotorsStatus指向一个C字符串。正如我已经指出的,你没有证明robotMotorsStatus指向任何明确的东西,即使它指向某个地方,你也没有证明内存的内容是一个C字符串
如果数组的实际边界内没有空字符,则该数组不包含C字符串,并且尝试读取整个C字符串,就像将数组传递给%s格式化程序一样,将在经过数组末尾后导致崩溃。如果robotMotorsStatus的另外两个通道不是你的崩溃,那么这一个可能是
这里的解决方案不仅是让指针变量指向您想要的地方,而且让包含空字符的有效C字符串完全位于该空间内
顺便提一下,这些问题与线程无关。只是想确定一下:您是否在某处定义了robotMotorsStatus?你有什么例外?你看过文档了吗?锁是什么样的东西;NSLock?在哪里称为changeRobotStatus:?你在别的地方锁门吗?还有什么可以进入机器人摩托状态?重申一下Yuji的问题,你有什么例外?
extern char *robotMotorsStatus;
string_to_send[7] = robotMotorsStatus[0];
string_to_send[8] = robotMotorsStatus[1];
robotMotorsStatus[0]='1';
NSLog (@"Robot status %s", robotMotorsStatus);