gpt4 book ai didi

与 os_unfair_lock_lock 的快速访问竞争

转载 作者:行者123 更新时间:2023-12-05 08:47:02 36 4
gpt4 key购买 nike

我制作了一个自定义属性包装器,它提供了一种使用 os_unfair_lock 在互斥上下文中访问数据的方法。在启用 TSAN 测试我的包装器后,在使用 os_unfair_lock_lock 获取锁时报告了访问竞争错误(如下图所示)

Access race image

不知何故,TSAN 报告了一个本应是线程安全的锁定结构,但实际上并非如此。这是怎么回事?

最佳答案

根据 WWDC 2016 演讲“在 Swift 3 中使用 GCD 进行并发编程”,演讲者在 18:07 左右指出

Traditionally you would use a lock. And in Swift, since you have the entire Darwin module at your disposition, you will actually see the struct based traditional C locks. However [emphasis added], Swift assumes that anything that's a struct can be moved, and that doesn't work with a mutex or with a lock.

解决方案是连接到 Objective-C 并创建一个将 os_unfair_lock 包装为 ivar 的类:

And if you want something that's smaller and that looks like the locks that you have in C, then you have to call into Objective-C and introduce a base class in Objective-C that has your lock as an ivar

在这种情况下,类似

UnfairLock.h

#ifndef UnfairLock_h
#define UnfairLock_h

@import Foundation;
@import os;

@interface UnfairLock : NSObject

-(void)unfairlyAcquire;
-(void)unlock;

@end


#endif /* UnfairLock_h */

不公平锁.m

#import <Foundation/Foundation.h>
#import "UnfairLock.h"

@implementation UnfairLock {
os_unfair_lock _lock;
}

-(instancetype)init {
self = [super init];

if (self) {
_lock = OS_UNFAIR_LOCK_INIT;
}

return self;
}


-(void)unfairlyAcquire {
os_unfair_lock_lock(&_lock);
}

-(void)unlock {
os_unfair_lock_unlock(&_lock);
}

@end

关于与 os_unfair_lock_lock 的快速访问竞争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68614552/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com