gpt4 book ai didi

concurrency - 使用 dispatch_async 的 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-12-04 02:29:47 36 4
gpt4 key购买 nike

我正在尝试通过 Objective-C++ 中的异步调度队列执行 block 。这是我正在尝试做的类片段...

class Blah {
public:
void dispatch(const EventPtr& event) {
dispatch_queue_t queue = dispatch_queue_create(_queueName.c_str(), NULL);
dispatch_async(queue, ^{
this->dispatchEventToSubscribers(event);
});
dispatch_release(queue);
}
protected:
Dude _dude;
void dispatchEventToSubscribers(const EventPtr& event) {
_dude.dispatchToSubscribers(event);
}
}

我在 dispatchEventToSubscribers 方法中得到一个 EXC_BAD_ACCESS。当我检查 _dude 的值是什么时,XCode 告诉我它超出了范围。我只能假设我以某种方式丢失了 this。检查并发文档:

For blocks that you plan to perform asynchronously using a dispatch queue, it is safe to capture scalar variables from the parent function or method and use them in the block. However, you should not try to capture large structures or other pointer-based variables that are allocated and deleted by the calling context. By the time your block is executed, the memory referenced by that pointer may be gone. Of course, it is safe to allocate memory (or an object) yourself and explicitly hand off ownership of that memory to the block.

那么如何在 this 对象上异步分派(dispatch)一个方法呢?

谢谢!

最佳答案

出于某种原因,使 event 的本地实例有效...我不确定为什么...即...

void dispatch(const EventPtr& event) {
dispatch_queue_t queue = dispatch_queue_create(_queueName.c_str(), NULL);
EventPtr eventPtr = event; //local instance...
dispatch_async(queue, ^{
this->dispatchEventToSubscribers(eventPtr);
});
dispatch_release(queue);
}

关于concurrency - 使用 dispatch_async 的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557120/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com