Search code examples
objective-cmultithreadingsemaphoreobjective-c++thread-sleep

Sleep or semaphore for background thread


I have third party code which creates a lot of threads with code like this:

while (true) {
    {
        my::Lock lock(&mMutex); // mutex implementation in c++
        if (!reseting) {
            // some code
            break;
        }
    }
    usleep(1000 / 20); // 20 time per second
}

I can rewrite this code with semaphore. What to use, semaphore or sleep? As I understood they work same. Semaphore will work little bit faster because we can immediately continue this thread when reset is changed.

Or maybe you have another idea how to do this better?


Implementation of my::Lock:

Lock::Lock(pthread_mutex_t *mutex) {
    _mutex = mutex;
    pthread_mutex_lock(_mutex);
}

Lock::~Lock() {
    pthread_mutex_unlock(_mutex);
}

Solution

  • You are correct that polling is an inefficient approach. This mutex lock implementation only makes it worse.

    You ask if a semaphore might be better pattern: It probably is, but I suspect you can do even better. Specifically, three asynchronous patterns come to mind:

    • The "completion handler" pattern, where the API call takes a block parameter which is a block of code that will be called when the asynchronous task is complete. This is ideal when you need a simple interface for informing the caller of the completion of the asynchronous task.

    • The "delegate-protocol" pattern, where the API would have a delegate property to specify who to inform and a protocol that defines what methods the delegate may or must implement. This is useful pattern where the interface for communicating updates is more complicated (e.g. not simply when the task is complete, but perhaps various progress updates, too).

    • The "notification" pattern (using NSNotificationCenter to inform other object(s) of status changes). This is useful if it's possible that more than one object may want to be informed of the completion of the task.

    Frankly, the choice may be dictated by the details of this third-party library. It's hard to assess on the basis of the information provided.