Roman  Ermolov
Roman Ermolov

Reputation: 7908

Wait until dispatch_async thread ends

I am newcomer in Objective C. I have an object, that creates new thread via GCD with dispatch_async in default queue. I use dispatch_semaphore_wait with timeout = 1sec in thread to check when I need to close this thread.

When i call "close" method, it send dispatch_semaphore_signal and thread closes. But sometimes thread lives some time after "close" method ended. How could I wait in my "close" method until thread ends?

Thx.

Upvotes: 0

Views: 969

Answers (1)

jkh
jkh

Reputation: 3266

Canonical answer to such a question: What are you trying to do?

I ask this because, first, you should neither need to know or care that there is a thread backing a GCD request and when it exits - that's entirely up to GCD to manage.

Second, you should always be suspicious of code that uses explicit timeouts (other than "FOREVER"). If you have any reason to ask yourself "Why 1 second? What happens if whatever event I'm waiting for takes more or less time than this?" then you are engaging in the kind of thinking that leads to polling, and polling is just BAD BAD (evil, wrong) design for pretty much everything but writing certain kinds of device drivers!

A far more reasonable approach is to use a completion callback at the end of your operation to signal that it's done, taking a fully async approach to programming and also following, in the process, one of the fundamental design principles of GCD.

It sounds to me, and I'm just guessing here, that you're taking an existing programming paradigm or way of thinking and erroneously applying it to GCD. An understandable mistake, but a mistake nonetheless.

Upvotes: 3

Related Questions