Skip to content

Instantly share code, notes, and snippets.

@juwencheng
Created October 5, 2018 00:56
Show Gist options
  • Select an option

  • Save juwencheng/ddeed34c4cec119440aa38f296fe78d5 to your computer and use it in GitHub Desktop.

Select an option

Save juwencheng/ddeed34c4cec119440aa38f296fe78d5 to your computer and use it in GitHub Desktop.

Revisions

  1. juwencheng created this gist Oct 5, 2018.
    6 changes: 6 additions & 0 deletions MultiThreadObject.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    @interface MultiThreadObject: NSObject
    @property (nonatomic, strong) NSArray *data;
    @end

    @implementation MultiThreadObject
    @end
    25 changes: 25 additions & 0 deletions demo1.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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];
    }
    }];