简体   繁体   中英

Does a GCD serial queue use all CPU cores?

i want to render 30 different images. Each task has to merge different image layers to just one final image- 30 final images.

Currently i use a GCD serial queue. Now i want to know if this approach uses the CPU power of all available cores automatically?

Or can i improve the rendertime for all these tasks when using a GCD concurrent queue instead? Thanks for clarification..

Serial queue = 1 task = 1 core. But the real problem in your use case is I/O contention. What happens if you spawn a concurrent queue to read from one resource? you end up with the CPU(s) sitting idle on each block while they take turns reading the disk. GCD reacts to idle CPU increasing the thread pool. In this case that results in too many threads and even more contention.

The solution is to use dispatch_io functions for the reading, and do the image processing on a different concurrent queue, which will be free to grow as needed.

dispatch_queue_t imageProcessing = dispatch_queue_create("com.yourReverseDomainHere", DISPATCH_QUEUE_CONCURRENT);

for (NSURL *url in ...){
    dispatch_io_t io = dispatch_io_create_with_path(DISPATCH_IO_RANDOM,[[url path] fileSystemRepresentation], O_RDONLY, 0, NULL, NULL);
    dispatch_io_set_low_water(io, SIZE_MAX);
    dispatch_io_read(io, 0, SIZE_MAX, dispatch_get_main_queue(),^(bool done, dispatch_data_t data, int error){

        // convert the file from dispatch_data_t to NSData
        const void *buffer = NULL;
        size_t size = 0;
        dispatch_data_t tmpData = dispatch_data_create_map(data, &buffer, &size);
        NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];
        dispatch_release(tmpData);
        free(buffer);

        // send this nsdata elsewhere for processing
        dispatch_async(imageProcessing, ^{
            // ...image processing code...
        });

    });
}

串行队列一次运行一个任务,因此每个串行队列一次仅使用一个内核(尽管在任何时候都不会使用哪个内核,并且可以更改)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM