iOS开发常用知识点

Dispatch I/O 本地读取

2018-12-17  本文已影响20人  HotCatLx

1.Dispatch I/O 简单介绍

/*! @header
 * Dispatch I/O provides both stream and random access asynchronous read and write operations on file descriptors. 
 * //同时提供了stream & random 两种异步文件读写操作

 * One or more dispatch I/O channels may be created from a file descriptor as either the DISPATCH_IO_STREAM type or DISPATCH_IO_RANDOM type.
 * // 可同时创建 DISPATCH_IO_STREAM &  DISPATCH_IO_RANDOM 单个或者多个channel

 * Once a channel has been created the application may schedule asynchronous read and write operations.The application may set policies on the dispatch I/O channel to indicate the desired frequency of I/O handlers for long-running operations.
 * // 一旦channel创建,应用会根据配置项去异步调度读写操作,APP会根据设置值去多线程文件操作来实现一个较长持续时间的I/O操作
 *
 * Dispatch I/O also provides a memory management model for I/O buffers that avoids unnecessary copying of data when pipelined between channels. 
 * //Dispatch I/O 也提供一个内存管理模型针对I/0 buffer ,以防止不必要的channel之间的拷贝数据
 
 * Dispatch I/O monitors the overall memory pressure and I/O access patterns for the application to optimize resource utilization.
 * //Dispatch I/O 监控APP 的总内存 和I/O访问模式,以优化资源利用率。
 */

2. 串行异步读取本地文件

2.1 代码
//为了验证设置单次读取大小,读取次数是否正确
static int serialNumberl = 0;

//异步串行读取文件
- (void)asyncSerialReadData {
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"md"];
    
    // 见2.2 解析1
     //dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
     
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 见2.2 解析2
    dispatch_io_t chanel = dispatch_io_create_with_path(DISPATCH_IO_STREAM, [path UTF8String], 0, 0, queue, ^(int error) {
        
    });
    
    // 见2.3 解析3
    size_t water = 1024;
    dispatch_io_set_low_water(chanel, water);
    dispatch_io_set_high_water(chanel, water);
    NSMutableData *totalData = [[NSMutableData alloc] init];
    
    //读取操作
    dispatch_io_read(chanel, 0, SIZE_MAX, queue, ^(bool done, dispatch_data_t  _Nullable data, int error) {
        
        if (error == 0) {
            // 单次读取大小
            size_t size = dispatch_data_get_size(data);
            if (size > 0 ) {
                [totalData appendData:(NSData*)data]; //拼接数据
            }
        }
        
        if (done) {
                // 完整读写结果
            NSString *str = [[NSString alloc] initWithData:totalData encoding:NSUTF8StringEncoding];
            NSLog(@"%@", str);
        }else {
            serialNumberl ++;
            NSLog(@"read not done,第%d次读取,在%@线程",serialNumberl,[NSThread currentThread]);
        }
        
        
    });
}

2.2 参数解析

background tasks. Threads created by pthread_create() without an attribute specifying a QOS class will default to QOS_CLASS_DEFAULT. This QOS class value is not intended to be used as a work classification, it should only be set when propagating or restoring QOS class values provided by the system.
//优先级低于 user-interactive配置项,这个QOS类value不涉及具体的工作内容,它应该只是传播或恢复系统提供的QOS类时默认设置。
*/
```

    /*!
     * dispatch_io_create_with_path
     * 
     * 根据path创建channel
     *
     * param type    The desired type of I/O channel (DISPATCH_IO_STREAM  or DISPATCH_IO_RANDOM) //DISPATCH_IO_STREAM顺序连续(serially)读取, DISPATCH_IO_RANDOM随机读取
    
     * param path    The absolute path to associate with the I/O channel. // 读取路径
     * param oflag    The flags to pass to open(2) when opening the file at path. 
     * param mode   
     * param queue    
     * param cleanup_handler   //回调
     */
    
```

dispatch_io_set_low_water // 单次读取mark的字节大小

* If an I/O handler requires intermediate results of fixed size, set both the low and and the high water mark to that size //如果I/O处理程序需要固定大小的中间结果,而不是单次随机的,则将low & high 值设置为相同的 *

3. 并发异步读取本地文件

3.1 代码
static int concurrentNumber = 0;

- (void)asyncConcurrentReadData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"md"];
    
    dispatch_queue_t queue = dispatch_queue_create("readDataQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();

    
    //见3.2 解析1
    dispatch_fd_t fd = open(path.UTF8String, O_RDONLY);
   
    dispatch_io_t io = dispatch_io_create(DISPATCH_IO_RANDOM, fd, queue, ^(int error) {
        close(fd);
    });
    
    
    long long fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;
    size_t offset = 128 * 128;
    
     NSMutableData *totalData = [[NSMutableData alloc] initWithLength:fileSize];
   
    for (off_t currentSize = 0; currentSize <= fileSize; currentSize += offset) {
        
        dispatch_group_enter(group);
        
        //dispatch_io_read默认异步
        dispatch_io_read(io, currentSize, offset, queue, ^(bool done, dispatch_data_t  _Nullable data, int error) {
            
            if (error == 0) {
                size_t size = dispatch_data_get_size(data);
                if (size > 0) {
                    dispatch_semaphore_wait(weakSelf.semaphore, DISPATCH_TIME_FOREVER);
                    [totalData appendData:(NSData*)data];
                    dispatch_semaphore_signal(weakSelf.semaphore);  
                }
                
            }
            
            if (done) {
                dispatch_group_leave(group);
            }else {
            NSLog(@"read not done,第%d次读取,在%@线程",concurrentNumberl,[NSThread currentThread]);
            }
            
        });
        
    }
    
    dispatch_group_notify(group, queue, ^{
        NSString *str = [[NSString alloc] initWithData:totalData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
    });
    
}

3.2 解析
上一篇 下一篇

猜你喜欢

热点阅读