Use semaphores to implement the sequential execution of threads

#import "ViewController.h"

@interface ViewController (){
    
    dispatch_semaphore_t _sema1;
    dispatch_semaphore_t _sema2;
    
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _sema1 = dispatch_semaphore_create(0);
    _sema2 = dispatch_semaphore_create(0);
    
    [NSThread detachNewThreadWithBlock:^{
        
        for (int i=0; i<50; i++) {
            
            NSLog(@"thread1");
            
        }
        
        dispatch_semaphore_signal(_sema1);
        
    }];
    
    [NSThread detachNewThreadWithBlock:^{
        
        for (int i=0; i<50; i++) {
            
            NSLog(@"thread2");
            
        }
        
        dispatch_semaphore_signal(_sema2);
        
    }];
    
    [NSThread detachNewThreadWithBlock:^{
        
        dispatch_semaphore_wait(_sema1, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(_sema2, DISPATCH_TIME_FOREVER);
        
        for (int i=0; i<50; i++) {
            
            NSLog(@"thread3");
            
        }
        
    }];
    
}

After thread 1 and thread 2 are executed, thread 3 is executed

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022700&siteId=291194637