Here is the code:
let serialQueue = DispatchQueue(label: "com.hello")
print("current:",Thread.current)
for i in 0...9 {
serialQueue.sync {
print(i,Thread.current)
}
}
print("hello world")
--------------------
output as below:
current: <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
0 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
1 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
2 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
3 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
4 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
5 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
6 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
7 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
8 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
9 <NSThread: 0x7f8dd5c0dfe0>{number = 1, name = main}
hello world
When I write down this code,I think there should be NO deadlock,and it works as expected.But once I saw the output, current thread and the thread which GCD used are the same thread! Why there is no thread deadlock when current thread and the thread which GCD used are the same thread? I thought a custom serial queue should not pick up main thread to run it's task, but it does, why?
Once I changed the serialQueue to DispatchQueue.main
, thread deadlock does happen,this is what I expected.
let serialQueue = DispatchQueue.main
print("current:",Thread.current)
for i in 0...9 {
serialQueue.sync {
print(i,Thread.current)
}
}
print("hello world")