• Dark Arc@social.packetloss.gg
    link
    fedilink
    English
    arrow-up
    4
    ·
    5 months ago

    It sounds like just from how you describe things Swift is using fibers instead of real OS threads(?)

    Seriously look at this comparison of DispatchQueue and OperationQueue

    What are these things/what is this comparing?

    • abhibeckert@lemmy.world
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      5 months ago

      is [Swift] using fibers instead of real OS threads(?)

      There are similarities to fibres, I’d say they’re solving the same problem, but they’re not really the same thing.

      It uses libdispatch which is built on top of “real OS threads” though on some kernels (especially BSD ones) it takes advantage of non-POSIX standard OS threading features (it can run without them, but runs better with them).

      Essentially you give the dispatcher a set of tasks, and the dispatcher will execute those tasks on as many threads as makes sense for the available hardware (this is where kernel integration helps, because the number of available CPU cores depends on the current workload for all processes, not just your process, and it changes from one millisecond to the next). The general goal is to keep every CPU core fully loaded, unless QoS has been set low which would prioritise battery life (and might, for example, use “efficiency cores” or avoid “turbo boost”).

      What are these things/what is this comparing?

      It’s a simple variable assignment, such as person.name = "bob", where the compiler has recognised the value might be accessed concurrently from multiple threads and may need to pause execution for a task that is waiting for the lock to be released. But of course, since the goal is to keep the CPU core active, it doesn’t just pause the code running on that core - it’s likely to start executing something else on the same core while waiting.

      OperationQueue and DispatchQueue are basically the same, but OperationQueue has additional scheduling / dependency features which come with a slight performance overhead. If your execution tasks are slow and have minimal interaction with other threads, such as resizing half a million images, then you wouldn’t notice the performance overhead. But if you have very short operations that interact with each other (or if you just don’t need any of those management features) then DispatchQueue is the way to go.

      They’re largely the same in basic use:

      dispatchQueue.async {
         // your code here
      }
      
      operationQueue.addOperation {
       // your code here
      }