Created
May 25, 2018 02:30
-
-
Save omochi/eedb0d692bf9d778e4c65b0b0955e087 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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)") | |
} | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DispatchQueueのスレッド関係の振る舞いについて調べてみました。
iOS実機で実行して調べました。
.sync
は呼び出しスレッドで実行される。キューのスレッドではない。.async
はキューのスレッドで実行される。513個目のキューには既存のスレッドが共有割当された。この数はおそらく環境によって変わるんだろう。