本文介绍了Cocoa线程同步时使用[ALAssetsLibrary enumerateGroupsWithTypes:]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近像几个人一样发现,[ALAssetsLibrary enumerateGroupsWithTypes]喜欢在另一个主题中执行其方块。很遗憾,苹果没有记录: - )



在我目前的情况下,我需要等待枚举完成,主线程返回任何结果之前。我显然需要某种类型的线程同步。



我读过关于NSLock& NSConditionLock,但没有什么似乎适合信号一个阻塞的线程,这个工作线程已经完成的要求。看起来像一个简单的需求 - 任何人都可以指向正确的方向?



你的线索&

解决方案
答案是使用NSConditionLock类这样...

  typedef枚举{
completed = 0,
running = 1
} threadState;

...

NSConditionLock * lock = [[NSConditionLock alloc] initWithCondition:running];

然后分离你的线程,或者在我的例子中调用[ALAssetsLibrary enumerateGroupsWithTypes:]。然后用这个...阻止父线程。

  //等待完成工作线程
[lock lockWhenCondition:完成];
[lock unlockWithCondition:completed];

子/工作线程中完成所有工作后, parent with this ...

  //等待线程信号
[lock lockWhenCondition:running];
[lock unlockWithCondition:completed];


I have recently, like a few people, discovered that [ALAssetsLibrary enumerateGroupsWithTypes] likes to run its blocks on another thread. What a shame that Apple didn't document that :-)

In my current circumstance I need to wait for the enumeration to complete, before the main thread returns any results. I clearly need some sort of thread synchronisation.

I've read about NSLock & NSConditionLock, but nothing yet seems to fit the requirement of 'signal a blocked thread that this worker thread has completed'. It seems like a simple enough need - can anyone point me in the right direction?

Your clue & boos, are most welcome as always,

M.

解决方案

The answer is to use the NSConditionLock class thusly ...

typedef enum {
    completed = 0,
    running = 1
} threadState;

...

NSConditionLock *lock = [[NSConditionLock alloc] initWithCondition:running];

Then spin off your thread, or in my case a call to [ALAssetsLibrary enumerateGroupsWithTypes:]. Then block the parent thread with this ...

// Await completion of the worker threads
[lock lockWhenCondition:completed];
[lock unlockWithCondition:completed];

When all work is done in the child/worker thread, unblock the parent with this ...

// Signal the waiting thread
[lock lockWhenCondition:running];
[lock unlockWithCondition:completed];

这篇关于Cocoa线程同步时使用[ALAssetsLibrary enumerateGroupsWithTypes:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:45