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

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

问题描述

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

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


  1. 主线程(M)可以提交请求到一些背景

  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.

什么是阻塞线程C的最好方法,直到线程B完成项目X?

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天全站免登陆