using dispatch_sync in Grand Central Dispatch

前端 未结 8 2092
孤城傲影
孤城傲影 2020-11-30 17:25

Can anyone explain with really clear use cases what the purpose of dispatch_sync in GCD is for? I can\'t understand where and why I would have to u

8条回答
  •  温柔的废话
    2020-11-30 17:41

    Here's a half-way realistic example. You have 2000 zip files that you want to analyze in parallel. But the zip library isn't thread-safe. Therefore, all work that touches the zip library goes into the unzipQueue queue. (The example is in Ruby, but all calls map directly to the C library. "apply", for example, maps to dispatch_apply(3))

    #!/usr/bin/env macruby -w
    
    require 'rubygems'
    require 'zip/zipfilesystem'
    
    @unzipQueue = Dispatch::Queue.new('ch.unibe.niko.unzipQueue')
    def extractFile(n)
        @unzipQueue.sync do
            Zip::ZipFile.open("Quelltext.zip") {   |zipfile|
                sourceCode = zipfile.file.read("graph.php")
            }
        end
    end
    
    Dispatch::Queue.concurrent.apply(2000) do |i|
       puts i if i % 200 == 0
       extractFile(i)
    end
    

提交回复
热议问题