iOS 上的上下文切换使用“performSelectorOnMainThread”

发布于 2025-01-02 17:47:55 字数 310 浏览 1 评论 0原文

我在 iOS 上遇到奇怪的线程问题。考虑这样一个简单的方法:

- (BOOL)doSomething
{
   [self doA];
   [self doB];
}

该方法应该在主线程的上下文中运行。我需要从工作线程调用此方法。为此,我使用performSelectorOnMainThread。

如果我按照这里解释的做所有事情。 doA`doB 之间可以发生上下文切换吗?

(我不这么认为,我只是想确保我的理解是正确的)

I have weird threading issues on iOS. Consider a simple method like this:

- (BOOL)doSomething
{
   [self doA];
   [self doB];
}

This method should only run in context of the main thread. I need to call this method from a worker thread. I use performSelectorOnMainThread for this purpose.

If I do everything as explained here. Can a context switch happen between doA and `doB?

(I don't think so, I just want to make sure that my understanding is right here)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停顿的约定 2025-01-09 17:47:55

通过“上下文切换”,我假设您的意思是主线程切换到其他一些主线程事件(因为您始终可以随时切换到另一个工作线程)。

但是,主线程将在执行其他操作之前完成所有 doSomething 操作。

摘自 performSelectorOnMainThread

该方法在主线程的运行循环上对消息进行排队
使用常见的运行循环模式,即与
NSRunLoopCommonModes 常量。 作为正常运行循环的一部分
处理时,主线程将消息从队列中取出(假设它是
以一种常见的运行循环模式运行)并调用所需的
方法。
从同一线程多次调用此方法会导致
相应的选择器要排队并在同一个中执行
调用的顺序。

By "context switch" I assume you mean the main thread switching to some other main thread event (as you could always switch to another worker thread at any time).

However, main thread will finish all of doSomething before doing anything else.

Excerpt from performSelectorOnMainThread:

This method queues the message on the run loop of the main thread
using the common run loop modes—that is, the modes associated with the
NSRunLoopCommonModes constant. As part of its normal run loop
processing, the main thread dequeues the message (assuming it is
running in one of the common run loop modes) and invokes the desired
method.
Multiple calls to this method from the same thread cause the
corresponding selectors to be queued and performed in the same same
order in which the calls were made.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文