跨线程事件信号(Obj-C)的同步/等待设计? [英] Synchronization/wait design for cross-thread event signaling (Obj-C)?

查看:24
本文介绍了跨线程事件信号(Obj-C)的同步/等待设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Cocoa 应用程序中,我有这样的设置:

In a Cocoa app, I have a setup like this:

  1. 主线程 (M) 可以向某个后台生产者"线程 (B) 提交请求以完成某些工作,例如对项目 X 的​​计算结果.
  2. 此后不久,另一个后台线程 (C) 可能想要计算项目 X 的​​结果,并希望这些结果同步.

线程 C 可以自己同步重做工作,但是如果线程 B 恰好在计算项 X 的中间,我希望线程 C 阻塞并从 B 获取结果.计算结果可以在磁盘上找到,因此数据传递不是问题.

Thread C could just re-do the work synchronously itself, but if thread B happens to be in the middle of computing item X already, I would like thread C to block and get the results from B. The results of the computation are findable on disk, so the data passing is not the issue.

在线程 B 完成项目 X 之前阻塞线程 C 的最佳方法是什么?

What's the best way of blocking thread C until thread B is done with item X?

请注意,B 处理的项目是任意的——X 只是此示例中的众多项目之一.我想阻止,直到特别项目 X 完成.

Note that there the items that B processes are arbitrary-- X is just one of many items in this example. I'd want to block until specifically item X is done.

所以从概念上讲,我希望线程 B 在开始说我正在处理 X"时设置某种标志,如果 C 进入并看到该标志,它会等待该标志清除,然后得到结果.

So conceptually what I'd like is a way of thread B setting up some sort of flag when it starts saying "I'm working on X", and if C comes in and sees that flag, it waits for the flag to clear, and then gets the result.

不确定我是否可以以某种方式将 NSLocks 硬塞到这个角色中,或者操作系统中是否有更好的原语.

Not sure if I can somehow shoehorn NSLocks into this role, or if there's a better primitive in the OS.

欢迎提出任何想法(或对问题的潜在重构)!谢谢.

Any thoughts (or potential reframing of the problem) welcome! Thanks.

推荐答案

如果可能,请使用 NSOperation.它有一个 -waitUntilFinished 方法来允许同步计算.你只需要一些线程安全的存储机制来让你找到你正在计算的项目的 NSOperation,如果它已经存在的话——比如说,一个 NSLock 保护NSDictionary.

If possible, use NSOperation. It has a -waitUntilFinished method to allow for synchronous computation. You'd just need some thread-safe storage mechanism to allow you to find the NSOperation for the item you're computing, if it already exists—say, an NSLock guarding an NSDictionary.

这篇关于跨线程事件信号(Obj-C)的同步/等待设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆