开发者

What can I do if two detached threads overlap each other? queue

开发者 https://www.devze.com 2023-01-13 06:25 出处:网络
I\'m not very \'up\' on multi-threading, but I\'ve been using detachNewThreadSelector in a couple of places to access data in a database. Unfortunately, on slo开发者_JS百科wer devices the first reques

I'm not very 'up' on multi-threading, but I've been using detachNewThreadSelector in a couple of places to access data in a database. Unfortunately, on slo开发者_JS百科wer devices the first request may still be happening when I call the second... Which naturally causes a crash because both are calling the same method (which is obviously not thread-safe).

What is the best way to go about sorting a bug like this? Can I somehow queue them so that the second thread doesn't start until the first one has finished?

Thanks!


You may want to have a look at NSOperation and NSOperationQueue which is an abstraction for a queue of tasks that can be run asynchronously from the main thread. If you want the NSOperationQueue to run just a NSOperation at a time (so to wait after the current task is compleate before firing the next one) you can just set the maxConcurrentOperationCount property of the queue to 1


To extend ranos answer a bit, be sure to add operations from the same thread because if you add several NSOperations from several threads, they will run concurrently, even though maxConcurrentOperationCount on NSOperationQueue is set to 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消