Skip to content

Instantly share code, notes, and snippets.

@juwencheng
Created October 5, 2018 00:56
Show Gist options
  • Save juwencheng/ddeed34c4cec119440aa38f296fe78d5 to your computer and use it in GitHub Desktop.
Save juwencheng/ddeed34c4cec119440aa38f296fe78d5 to your computer and use it in GitHub Desktop.
iOS多线程问题演示
MultiThreadObject *object = [[MultiThreadObject alloc] init];
NSLock *lock = [[NSLock alloc] init];
[NSThread detachNewThreadWithBlock:^{
NSInteger loopCount = 1000;
while (loopCount) {
[lock lock];
NSArray *data = @[@"1", @"2", @"3"];
object.data = data;
if (object.data != data) {
NSLog(@"多线程同步问题 self.data: %@, data: %@",object.data, data);
}
loopCount --;
[lock unlock];
}
}];
[NSThread detachNewThreadWithBlock:^{
NSInteger loopCount = 1000;
while (loopCount) {
[lock lock];
NSArray *data = @[@"1", @"2", @"3", @"4"];
object.data = data;
loopCount --;
[lock unlock];
}
}];
@interface MultiThreadObject: NSObject
@property (nonatomic, strong) NSArray *data;
@end
@implementation MultiThreadObject
@end
@juwencheng
Copy link
Author

重现步骤

  1. 创建一个共享变量object,其类型为MultiThreadObject
  2. 开启两个线程,对object.data设值,在同一个线程中,设置值后立马取出来和传入参数进行对比
  3. 如果不加锁(NSLock,synchronized等),在控制台会输出“多线程同步问题...”
  4. 如果加锁,结果如预期。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment