简体   繁体   中英

Serial OperationQueue with Operations synchronizing timer and sleep

I have a serial OperationQueue whose operations call usleep. I do this because the operation execution block synchronizes with a Timer that needs to repeat until a designated time.

For example, 3 operations are added to a queue with a maxconcurrent set to 1. Each operations has a timer that repeats until 10 seconds into the future. Upon firing this timer of the first operation, the next line of code is usleep(10seconds). 10 seconds later the timer completes and the thread wakes up. The next operation begins. This is done by design and works, however, I'm concerns about the implications about a sleeping thread. Is it possible that the thread was handling some other code, context switches to handle the operation, then sleeps for a long time, pausing other executions. Does swift know to let the thread execute other blocks while the operation sleeps?

Does swift know to let the thread execute other blocks while the operation sleeps?

Maybe it's just a wording issue, but the thread is blocked until the sleep (and subsequent tasks) finish, so it's not going to be made available to do anything else. But, while the thread is sleeping, the core can switch contexts to let some other thread run even though the thread running the operation is tied up.

So using usleep (or I might use Thread.sleep(forTimeInterval: 10) ) avoids the problem of blocking the core, but it still blocks the thread. And threads are rather limited (eg 64 at this point). So, especially if you might have a lot of these operations going on at any given time, thereby risking exhausting the limited threads, I might advise avoid blocking the thread, too. (Then again, if you're using a maxConcurrentOperationCount of 1, as long as you aren't doing other things that might tie up threads, it probably wouldn't be too serious of a problem.)

For example, I might define an asynchronous Operation subclass, and rather than sleeping, I might just asyncAfter (or use a timer) the finishing of the operation to 10 seconds in the future. That way no thread is blocked, either. Or I might consider other patterns to solve the broader problem. It's hard to say without knowing the broader problem that you're trying to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM