Skip to content

Instantly share code, notes, and snippets.

@omochi
Created May 25, 2018 02:30
Show Gist options
  • Save omochi/eedb0d692bf9d778e4c65b0b0955e087 to your computer and use it in GitHub Desktop.
Save omochi/eedb0d692bf9d778e4c65b0b0955e087 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// DispatchQueueTest
//
// Created by omochimetaru on 2018/05/25.
// Copyright © 2018年 Qoncept, Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UITapGestureRecognizer()
self.view.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.addTarget(self, action: #selector(onTap))
}
@objc func onTap() {
// test1()
test2()
}
func test1() {
let q1 = DispatchQueue(label: "q1")
NSLog("%@", "test1: \(Thread.current)")
q1.sync {
NSLog("%@", "test2: \(Thread.current)")
}
q1.async {
sleep(1)
NSLog("%@", "test3: \(Thread.current)")
}
q1.sync {
NSLog("%@", "test4: \(Thread.current)")
}
}
func test2() {
let qs = (0..<600).map { index in
DispatchQueue(label: "q\(index)")
}
var qToThread: [Int: Thread] = [:]
qs.enumerated().forEach { (index, q) in
q.async {
let th = Thread.current
DispatchQueue.main.sync {
qToThread.forEach { (k, v) in
if v == th {
NSLog("%@", "queue\(index): thread sharing found: queue \(k) also use \(v)")
}
}
qToThread[index] = th
}
sleep(1)
}
}
qs.enumerated().forEach { (index, q) in
q.async {
let th = Thread.current
let oldTh = (DispatchQueue.main.sync {
qToThread[index]! })
if oldTh != th {
NSLog("%@", "queue\(index): thread associatetion changed: , old=\(oldTh), th=\(th)")
}
}
}
}
}
@omochi
Copy link
Author

omochi commented May 25, 2018

DispatchQueueのスレッド関係の振る舞いについて調べてみました。
iOS実機で実行して調べました。

  1. .sync は呼び出しスレッドで実行される。キューのスレッドではない。
  2. .async はキューのスレッドで実行される。
  3. 複数のキューがスレッドを共有する事がある。ワーカースレッド512本まではキューのために新しいスレッドが立つが、
    513個目のキューには既存のスレッドが共有割当された。この数はおそらく環境によって変わるんだろう。
  4. キューに割り当てられたスレッドが変更される事は無さそうだった。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment