使用dispatch_async的EXC_BAD_ACCESS
我正在尝试通过 Objective-C++ 中的异步调度队列执行块。这是我正在尝试执行的操作的类片段...
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
。检查并发文档:
对于您计划执行的块 使用调度队列异步, 捕获标量变量是安全的 来自父函数或方法并且 在块中使用它们。然而,你 不应该尝试捕获大 结构体或其他基于指针的 分配的变量和 被调用上下文删除。由 当你的块被执行时, 该指针引用的内存可能 走吧。当然,这是安全的 分配内存(或对象) 自己并明确地交出 该内存对该块的所有权。
那么如何在 this
对象上异步分派方法呢?
谢谢!
I'm attempting to execute a block via an asynchronous dispatch queue in Objective-C++. Here's a class fragment of what I'm trying to do...
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);
}
}
I get a EXC_BAD_ACCESS within the dispatchEventToSubscribers method. When I check to see what the value of _dude
is, XCode tells me it is out of scope. I can only assume that I'm losing this
somehow. Checking the concurrency docs:
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.
So how do I dispatch asynchronously a method on this
object?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于某种原因,制作
event
的本地实例有效...我不知道为什么...即..For some reason, making a local instance of
event
worked...I'm not sure why...i.e...看来没有什么问题。确保块执行时 Blah 实例处于活动状态。 Blocks 自动保留 Objective-C 实例。不适用于 C++ 实例。
It seems there are no problems. Make sure the Blah instance is alive when the block executes. Blocks automatically retains Objective-C instances. not for C++ instances.