双重检查锁定 - 目标 c

发布于 2024-09-04 04:43:46 字数 753 浏览 2 评论 0原文

我意识到由于内存模型,双重检查锁定在 Java 中存在缺陷,但这通常与单例模式和优化单例的创建相关。

在 Objective-c 中的这种情况下怎么样:

我有一个布尔标志来确定我的应用程序是否正在流式传输数据。我有 3 个方法,startStreaming、stopStreaming、streamingDataReceived,并且我使用以下方法保护它们免受多个线程的影响:

- (void) streamingDataReceived:(StreamingData *)streamingData {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) stopStreaming {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
    if (!self.isStreaming) {
        @synchronized(self) {
            if (!self.isStreaming) {

此双重检查是否不必要?双重检查在objective-c中是否有与java中类似的问题?此模式(反模式)的替代方案是什么?

谢谢

I realised double checked locking is flawed in java due to the memory model, but that is usually associated with the singleton pattern and optimizing the creation of the singleton.

What about under this case in objective-c:

I have a boolean flag to determine if my application is streaming data or not. I have 3 methods, startStreaming, stopStreaming, streamingDataReceived and i protect them from multiple threads using:

- (void) streamingDataReceived:(StreamingData *)streamingData {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) stopStreaming {
    if (self.isStreaming) {
        @synchronized(self) {
            if (self.isStreaming) {

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
    if (!self.isStreaming) {
        @synchronized(self) {
            if (!self.isStreaming) {

Is this double check uneccessary? Does the double check have similar problems in objective-c as in java? What are the alternatives to this pattern (anti-pattern).

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风为裳 2024-09-11 04:43:46

它同样有缺陷 - 你有一个竞争条件

你必须输入你的同步部分,然后检查标志

It is equally flawed - you have a race condition

You have to enter your synchronized section and then check the flag

蘸点软妹酱 2024-09-11 04:43:46

对我来说,这看起来像是过早的优化。有什么问题(例如)

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
        @synchronized(self) {
            if (!self.isStreaming) {
...

That looks like premature optimisation to me. What's wrong with (for example)

- (void) startStreaming:(NSArray *)watchlistInstrumentData {
        @synchronized(self) {
            if (!self.isStreaming) {
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文