• dispatch普通人不常用


    文件数据库读写读取可以并行,写入必须串行,如果在读写之后插入写入操作,可以通过dispatch_barrier_async操作加入到并行队列中,此时队列会按并行的方式执行完之前加入的操作,然后以串行的方式执行写入的代码,之后恢复正常处理逻辑

    dispatch_apply函数,指定函数执行次数N,插入某个队列中,并且当前线程会等待函数N次执行完成之后继续执行,apply带有参数index表明区分

    dispatch_block_cancel可以取消执行加入到队列中通过dispatch_block_create创建的block

    dispatch_semaphore_t 当计数值大于1时,dispatch_semaphore_wait带参数等待时长,与dispatch_group_wait时间参数一致,如果是永远等待dispatch_time_forever,那么除非等待到计数大于1,否则代码执行将卡在这里。如果时长设定不为永远,则在等待时间过去之后会继续执行下面的代码,通过函数的返回值可以确定是否为等待到了信号量并将其减去了1

    通过函数 dispatch_semaphore_signal可以将引用计数加1,这样别的地方就能正确执行下去了,可以参照看过的音频播放代码

    多线程读取文件

    int file = open("x.txt", O_RDONLY);
        __block size_t handleSize = 0;
        size_t readSize = 1024;
        char *buff = (char*)malloc(readSize);
        //设置标记 F_SETFL  file set flag   O_NONBLOCK  异步映像
        fcntl(file, F_SETFL,O_NONBLOCK);
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, file, 0, queue);
        dispatch_source_set_event_handler(source, ^{
            size_t available = dispatch_source_get_data(source);
            size_t length = read(file, buff, available);
            if (length < 0) {
                /*
                 错误处理
                 */
                dispatch_source_cancel(source);
            }
            else {
                handleSize += length;
                if (handleSize == readSize) {
                    /*
                     处理读取结束
                     */
                    dispatch_source_cancel(source);
                }
            }
        });
        dispatch_source_set_cancel_handler(source, ^{
            free(buff);
            close(file);
        });
        dispatch_resume(source);
  • 相关阅读:
    (转)C#中Thread.sleep()
    ZigBee无线信道组成
    JSP应用html乱码的终极解决办法
    How to size text using ems
    iframe和frame的区别
    [洛谷P2827]蚯蚓
    [洛谷P3391]【模板】文艺平衡树(Splay)
    [洛谷P4180]严格次小生成树
    HTTP 常见鉴权
    使用 rsync 备份/复制 系统
  • 原文地址:https://www.cnblogs.com/yuxiaoyiyou/p/11301163.html
Copyright © 2020-2023  润新知