我的员工中相当丑陋和粗暴的事情是这样的:NSLog(@"paused");暂停 = 是;同时(暂停){[NSThread sleepForTimeInterval:0.25];}NSLog(@"...继续");...但我不禁想到一定有更好的方法,也许涉及 NSLocks 或类似的方法.评论、提示建议?谢谢! 解决方案 查看 NSCondition 和 条件 线程指南中的部分.代码将类似于:NSCondition* 条件;//初始化和释放这是您的应用程序需要的.//工作线程:while([NSThread currentThread] isCancelled] == NO){【条件锁定】;while(partySuppliesAvailable == NO){[条件等待];}//派对!派对用品可用 = 否;【条件解锁】;}//主线程:【条件锁定】;//获取派对用品派对用品可用 = 是;【状态信号】;【条件解锁】;I have a worker thread that I want to do one bit of its task, then pause & wait for the "ok, continue" command from another thread, then pause & wait, etc.The use case is: the controlling object is a view that I want to display information about what's going on inside the worker-thread, and allow me to "single-step" through the worker as it does it's thing.The rather ugly and heavy-handed thing that I have in my worker is this:NSLog(@"paused");paused = YES;while (paused){ [NSThread sleepForTimeInterval:0.25];}NSLog(@".. continuing");...But I can't help but think that there must be a nicer way, perhaps involving NSLocks, or some such.Comments, hints suggestions?Thanks! 解决方案 Look into NSCondition and the Conditions section in the Threading guide. The code will look something like:NSCondition* condition; // initialize and release this is your app requires.//Worker thread:while([NSThread currentThread] isCancelled] == NO){ [condition lock]; while(partySuppliesAvailable == NO) { [condition wait]; } // party! partySuppliesAvailable = NO; [condition unlock];}//Main thread:[condition lock];// Get party suppliespartySuppliesAvailable = YES;[condition signal];[condition unlock]; 这篇关于如何暂停 NSThread 直到收到通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 04:39