简体   繁体   English

Swift中的线程间通信?

[英]Inter-thread communication in Swift?

My goal is to parse a large XML file (20 GB) with Swift. 我的目标是使用Swift解析一个大型XML文件(20 GB)。 There are some performance issues with NSXMLParser and bridging to Swift objects, so I'm looking at multi-threading. NSXMLParser和Swift对象的桥接存在一些性能问题,因此我正在研究多线程。 Specifically the following division: 具体如下划分:

  1. Main thread - parses data 主线程 - 解析数据
  2. Worker thread - casts ObjC types into Swift types and sends to 1. The casting of ObjC NSDictionary to [String: String] is the largest bottleneck. 工作线程 - 将ObjC类型转换为Swift类型并发送到1.将ObjC NSDictionary转换为[String:String]是最大的瓶颈。 This is also the main reason for separating onto multiple threads. 这也是分离到多个线程的主要原因。
  3. Worker thread - parses XML into ObjC types - and sends to 2. NSXMLParser is a push-parser, once it starts parsing, you cannot pause it. 工作线程 - 将XML解析为ObjC类型 - 并发送到2. NSXMLParser是一个推送解析器,一旦开始解析,就不能暂停它。

The data should be parsed sequentially, so the input ordering should be maintained. 应该按顺序解析数据,因此应保持输入顺序。 My idea is to run an NSRunLoop on both 1 and 2, allowing parallel processing without blocking. 我的想法是在1和2上运行NSRunLoop,允许并行处理而不会阻塞。 According to Apple's documentation, communication between the threads can be achieved by calling performSelector:onThread:withObject:waitUntilDone: . 根据Apple的文档,线程之间的通信可以通过调用performSelector:onThread:withObject:waitUntilDone: However this symbol is not available in Swift. 但是,此符号在Swift中不可用。

I don't think that GCD would fit as a solution. 我认为GCD不适合作为解决方案。 Both worker threads should be long-running processes with new work coming in at random intervals. 两个工作线程都应该是长时间运行的进程,新的工作会以随机的间隔进行。

How can one achieve the above (eg NSRunLoops on multiple threads) using Swift? 如何使用Swift实现上述目标(例如多线程上的NSRunLoops)?

I used NSOperation for the first time last month, and it's is a really easy object to subclass, you could either chain them together with completion blocks, or you can set operations to be dependencies of each other so that they're performed sequentially. 我上个月第一次使用NSOperation ,它是一个非常容易的子类对象,你可以将它们与完成块链接在一起,或者你可以将操作设置为彼此的依赖关系,以便它们按顺序执行。

It's also pretty easy to communicate with NSOperations by passing in objects to them. 通过向对象传递对象,与NSOperations进行通信也非常容易。

NSHipster: http://nshipster.com/nsoperation/ NSHipster: http ://nshipster.com/nsoperation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM