zoukankan      html  css  js  c++  java
  • 信号量与并发控制

    代码1 - 未使用信号量控制并发:

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (NSUInteger i = 0;  i < 10; ++i) {
                NSLog(@"Task - 1");
            }
        });
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (NSUInteger i = 0;  i < 10; ++i) {
                NSLog(@"Task - 2");
            }
        });
    }
    
    @end

    输出:

    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2
    Task - 1
    Task - 2

    代码 - 使用信号量控制并发:

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @property (nonatomic, strong) dispatch_semaphore_t semaphore;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.semaphore = dispatch_semaphore_create(1);
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
            for (NSUInteger i = 0;  i < 10; ++i) {
                NSLog(@"Task - 1");
            }
            dispatch_semaphore_signal(self.semaphore);
        });
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
            for (NSUInteger i = 0;  i < 10; ++i) {
                NSLog(@"Task - 2");
            }
            dispatch_semaphore_signal(self.semaphore);
        });
    }
    
    @end

    输出:

    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 1
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
    Task - 2
  • 相关阅读:
    操作系统六文件管理
    Educational Codeforces Round 38 (Rated for Div. 2) ABCD
    51nod 1100 斜率最大
    51nod 最小方差
    51nod 1065 最小正子段和
    P1280 尼克的任务
    牛客小白月赛2
    Codeforces Round #210 (Div. 1) B 二分+dp
    江西财经大学第一届程序设计竞赛
    51nod 1596 搬货物
  • 原文地址:https://www.cnblogs.com/xwoder/p/7460783.html
Copyright © 2011-2022 走看看