gpt4 book ai didi

IOS - 线程在 Web 服务调用期间停止

转载 作者:行者123 更新时间:2023-11-29 12:54:25 24 4
gpt4 key购买 nike

我正在运行一个有多个线程的应用程序。我的应用程序有一组队列对象(简单的数组)。线程的输入将来自这个队列。每个线程都会得到一个队列对象作为输入。我正在以如下简单的方式创建和启动此线程。

threadOne = [[NSThread alloc] initWithTarget:self
selector:@selector(initThread:)
object:nil];
[threadOne main];

同样,我为每个对象启动了多个可用线程。

当我在我的网络服务调用期间以 Debug模式运行我的应用程序时,我当前运行的线程不等待响应(我的网络服务调用大约需要 2-3 秒来生成响应)。在这里,我的队列进程由于 Web 服务调用而停止。以下是引用代码。

dispatch_sync(dispatch_get_main_queue(), ^{

[service genID:self action:@selector(genHandler:) username: username password:password ];

});

我想在我的应用程序中并行运行多个线程。是否有任何解决方案可以实现上述目标。

最佳答案

你可能有一个死锁,因为你正在调用

dispatch_sync(dispatch_get_main_queue()

来自主线程。您可以在 this answer 中找到很好的解释.

作为旁注,我建议使用 NSOperationQueue 或 Grand Central Dispatch,因为 Apple does not recommend直接使用 NSThread 对象:

In the past, introducing concurrency to an application required the creation of one or more additional threads. Unfortunately, writing threaded code is challenging. Threads are a low-level tool that must be managed manually. Given that the optimal number of threads for an application can change dynamically based on the current system load and the underlying hardware, implementing a correct threading solution becomes extremely difficult, if not impossible to achieve. In addition, the synchronization mechanisms typically used with threads add complexity and risk to software designs without any guarantees of improved performance.

Both OS X and iOS adopt a more asynchronous approach to the execution of concurrent tasks than is traditionally found in thread-based systems and applications. Rather than creating threads directly, applications need only define specific tasks and then let the system perform them. By letting the system manage the threads, applications gain a level of scalability not possible with raw threads. Application developers also gain a simpler and more efficient programming model.

关于IOS - 线程在 Web 服务调用期间停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529458/

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