线程本地存储和iOS [英] Thread-Local storage and iOS

查看:405
本文介绍了线程本地存储和iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,iOS不支持 __线程。显然,有一种方法可以使用 pthread_setspecific 。但是,是否已经有一个模板类实现了这个功能?



我会重新发明轮子,特别是因为它不会是一个简单的



任何链接都将非常感谢!



b

解决方案

Foundation提供 - [NSThread threadDictionary] 。你可以使用它来存储线程本地的Objective-C对象,它可以包含一个 NSValue 包装任何动态存储的地址。



注意,Cocoa正在向线程代码的线程执行,你提交代码块,以在任何可用的系统拥有的线程上运行。这是Grand Central Dispatch和共享 NSOperationQueue 使用的模型。依赖线程本地存储的代码将无法充分利用此模型。有关详情,请参阅Apple的并发编程指南。 p>

ETA:从iOS 5 / OS X 10.7开始,Grand Central Dispatch通过 dispatch_queue_set_specific dispatch_queue_get_specific dispatch_get_specific 函数。除了为键设置新值或当队列被销毁时,设置器还允许提供析构函数。 getter sans queue使用当前队列作为上下文,并且如果当前队列上没有定义键(类似于原型OO系统中的属性查找工作原理),则将重复对当前队列的目标队列的查找。


My understanding is that iOS does not support __thread. There is, obviously, a way to do this using pthread_setspecific. However, is there already a template class that has implemented this functionality?

I'd ate to re-invent the wheel, especially as it won't be a simple piece of code to write.

Any links would be hugely appreciated!

Cheers

解决方案

Foundation provides -[NSThread threadDictionary]. You can use this to store thread-local Objective-C objects, which could include an NSValue wrapping the address of any dynamic storage.

Note that Cocoa is moving towards thread-blind execution of threaded code, where you submit blocks of code to be run on any available system-owned thread. This is the model used by Grand Central Dispatch and the shared NSOperationQueues. Code relying on thread-local storage will not make the best use of this model. See Apple's Concurrency Programming Guide for more info.

ETA: Starting with iOS 5 / OS X 10.7, Grand Central Dispatch gained what you could call queue-local storage via the dispatch_queue_set_specific, dispatch_queue_get_specific, and dispatch_get_specific functions. The setter allows you to supply a destructor function in addition to the value for when you set a new value for the key or when the queue is destroyed. The getter sans queue uses the current queue as context, and will repeat the lookup on the current queue's target queue if the key is not defined on the current queue (similar to how property lookup in a prototypal OO system works).

这篇关于线程本地存储和iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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