在类的初始化方法中,我将线程声明为:
NSThread* myThread = [[[NSThread alloc] initWithTarget:self selector:@selector(m_run_thread) object:nil] autorelease];
[myThread start]; 我还有一个布尔值,它被设置为NO。在后面的代码中,我将布尔值设置为YES。
bool_run_progress_thread =是;
m_run_thread方法的内容如下:
-(void) m_run_thread
{
if (bool_run_progress_thread)
{
//do processing here
}
bool_run_progress_thread = NO;
}问题是m_run_thread方法永远不会被访问。我做错了什么?
附注:我也尝试过使用以下(以及更老的)方法设置线程:
[NSThread detachNewThreadSelector:@selector(m_run_thread)
toTarget:self
withObject:nil];..。但也无济于事。
发布于 2012-05-17 20:27:12
"...and我只让它显示一次“是的,这正是它应该显示的样子。启动后,线程从开始到结束运行一次(暂时忽略这里的错误),在到达结束时,线程基本上是死的。
如果你想让线程重复执行,你必须自己做好准备:
- (void) m_run_thread
{
for (;;)
{
if (bool_run_progress_thread)
{
//do processing here
bool_run_progress_thread = NO;
}
}
}但这段代码仍然有很多错误:本质上,当运行时,代码会形成一个繁忙的等待循环。假设bool_run_progress_thread只在很短的一段时间内为真,后台线程应该在大部分时间处于休眠状态。在欧洲工商管理学院,如果你尝试将代码作为替代,它将消耗CPU时间(并且大量的CPU时间)。
一种更好的方法是使用condition variables
@class Whatsoever
{
NSCondition* cvar;
BOOL doProgress;
...
}
...
@end和
- (void) m_run_thread
{
for (;;)
{
[cvar lock];
while (!doProgress)
{
[cvar wait];
}
doProgress = NO;
[cvar unlock];
... do work here ...
}
}为了触发执行,你需要这样做:
- (void) startProgress
{
[cvar lock];
doProgress = YES;
[cvar signal];
[cvar unlock];
}这样做还需要注意另一个微妙的问题:对全局标志(您的bool_run_progress_thread,我的doProgess)所做更改的可见性。根据处理器及其内存顺序的不同,在没有特殊保护的情况下所做的更改可能会对其他线程可见,也可能不会。这个问题也是由NSCondition处理的。
https://stackoverflow.com/questions/10634093
复制相似问题