NSCondition: wait for a specified amount of time

不问归期 提交于 2019-12-12 03:57:35

问题


I'm developing an iOS 5.0+ app with latest SDK.

This app is a migration from an Android app.

On the Android app I have this code:

private Object uploadWorkerLock = new Object();
private static final int UPLOAD_WORKER_SLEEP_TIME = 30000;

[ ... ]

synchronized (ServerManager.this.uploadWorkerLock) {
    try {
        ServerManager.this.uploadWorkerLock.wait(UPLOAD_WORKER_SLEEP_TIME);
    } catch (InterruptedException e) {
        return;
    }
}

I've a problem with void java.lang.Object.wait(long millis). I can migrate that code this way:

NSCondition* uploadWorkerLock;

[ ... ]
[uploadWorkerLock lock];
[uploadWorkerLock wait];
[uploadWorkerLock unlock];

Reading Java documentation about wait(long), I have read this:

Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

I know I can invoke [uploadWorkerLock invoke] but how can I simulate that the specified amount of time has elapsed.?

By the way, this code is inside of a NSThread selector.


回答1:


If you want to do it simply, with a syntax similar to Java just to don't get confused, that's how to do it:

@synchronized(uploadWorkerLock)
{
    usleep(UPLOAD_WORKER_SLEEP_TIME*1000);
}

But this isn't the only way, the @synchronized directive isn't as fast as spin locks, or a NSLock. Another way is GCD, which allows you to execute some blocks of code (virtually) at the same time. It is faster than using separate threads, because it will try to optimize things, and it can run two separated blocks of code in the same thread, just simulating multithreading so avoiding context swapping which is expensive.

Also with GCD it isn't hard to do it, but it requires some additional knowledge of blocks and things that can be a bit messy for who just started with Objective-C. Also, GCD isn't a substitute for multithreading, when you have a complex application and every thread doesn't just execute a single block of code, plain multithreading will be more proper.



来源:https://stackoverflow.com/questions/16104678/nscondition-wait-for-a-specified-amount-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!