gpt4 book ai didi

objective-c - 简单的多线程应用程序有时会失败

转载 作者:行者123 更新时间:2023-12-03 16:28:58 27 4
gpt4 key购买 nike

我正在做这个多线程应用程序只是为了看看@synchronized指令是如何工作的。我读到如果所有线程都有相同的对象作为@synchronized的参数,那么它们都在同一个锁上等待。所以我想使用 self 作为参数,因为它对于所有线程都是相同的。
在此应用程序中,有一个文本字段被所有线程多次编辑。我不关心性能,这只是一个测试,因此我不会将 @synchronized 指令放在 for 之前,但在里面。

我使用的属性:

@property (weak) IBOutlet NSTextField *textField;
@property (nonatomic, copy) NSNumber* value;
@property (nonatomic,copy) NSMutableArray* threads;

代码:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
value= @0;
textField.objectValue= value;
for(int i=0; i<10; i++)
{
NSThread* thread=[[NSThread alloc]initWithTarget: self selector: @selector(routine:) object: nil];
[threads addObject: thread];
[thread start];
}
}

- (void) routine : (id) argument
{
for(NSUInteger i=0; i<100; i++)
{
@synchronized(self)
{
value= @(value.intValue+1);
textField.objectValue= value;
}
}
}
有时应用程序成功,我看到 1000 作为文本字段值。但有时不是,我担心这是饥饿,我在文本字段上看不到任何内容,它是空的。我尝试了调试,但很难看看哪里出了问题,因为失败的标准对我来说似乎很随意,有时它工作得很好。

解决方案

@synthesize threads,value, textField;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
value= @0;
threads=[[NSMutableArray alloc]initWithCapacity: 100];
for(NSUInteger i=0; i<100; i++)
{
NSThread* thread=[[NSThread alloc]initWithTarget: self selector: @selector(routine:) object: nil ];
[threads addObject: thread];
[thread start];
}
}

- (void) routine : (id) arg
{
for(NSUInteger i=0; i<1000; i++)
{
@synchronized(self)
{
value= @(value.intValue+1);
[textField performSelectorOnMainThread: @selector(setObjectValue:) withObject: value waitUntilDone: NO];
}
}
}

最佳答案

您正在从非主线程访问 NSTextField,它是 NSView 的子类。 That is not a safe thing to do 。结果未定义;有时似乎有效,有时则无效。

关于objective-c - 简单的多线程应用程序有时会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13536363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com