Skip to content

Instantly share code, notes, and snippets.

@noppefoxwolf
Created June 15, 2021 04:12
Show Gist options
  • Save noppefoxwolf/9b2375e7661649a612d244694295209f to your computer and use it in GitHub Desktop.
Save noppefoxwolf/9b2375e7661649a612d244694295209f to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// a
//
// Created by Tomoya Hirano on 2021/06/15.
//
import UIKit
class ViewController: UIViewController {
static let dispatchQueue = DispatchQueue(label: "test")
override func viewDidLoad() {
super.viewDidLoad()
ViewController.dispatchQueue.async {
Thread.current.name = "test thread"
print("done")
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
threadIDs().forEach { id in
print(threadName(id: id))
}
}
func threadIDs() -> [UInt32] {
var threadList = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
var threadCount = UInt32(MemoryLayout<mach_task_basic_info_data_t>.size / MemoryLayout<natural_t>.size)
let result = withUnsafeMutablePointer(to: &threadList) {
$0.withMemoryRebound(to: thread_act_array_t?.self, capacity: 1) {
task_threads(mach_task_self_, $0, &threadCount)
}
}
if result != KERN_SUCCESS { return [] }
var ids: [UInt32] = []
for index in (0..<Int(threadCount)) {
ids.append(threadList[index])
}
return ids
}
func threadName(id: UInt32) -> String {
var threadInfo = thread_extended_info()
var threadInfoCount = UInt32(THREAD_INFO_MAX)
let result = withUnsafeMutablePointer(to: &threadInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
thread_info(id, UInt32(THREAD_EXTENDED_INFO), $0, &threadInfoCount)
}
}
let name = withUnsafePointer(to: threadInfo.pth_name) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: $0)) {
String(cString: $0)
}
}
return name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment