【网络安全】CFRunloop的多线程隐患

如果你还不了解什么是runloop,可以看这里的详解深入理解RunLoop

苹果官方文档中,声明了CFRunloop是线程安全的:

Thread safety varies depending on which API you are using to manipulate your run loop. The functions in Core Foundation are generally thread-safe and can be called from any thread. If you are performing operations that alter the configuration of the run loop, however, it is still good practice to do so from the thread that owns the run loop whenever possible.

但是需要注意的是,狡猾的苹果使用了generally这个模糊的词。

从实践中来看,CFRunloop在停止runloop的阶段的某些操作是存在多线程隐患的。

不安全的CFRunloopSource

CFRunloop是线程安全的,但是加上CFRunloopSource就不一定了。比如CFSocket。

示例代码

看这样一段自定义线程的代码:

@interface MyThread()
@property (nonatomic, strong) NSThread *currentThread;
@property (nonatomic, assign) CFRunLoopSourceRef socketSource;
@property (nonatomic, assign) CFSocketRef socket;
@property (nonatomic, assign) CFRunLoopRef currentRunloop;

@end

@implementation MyThread

//初始化线程
- (instancetype)init {if (self = [super init]) {_currentThread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];}return self;
}

//开启线程;此方法在使用时没有多线程调用
- (void)startThread {[self.currentThread start];
}

//线程入口
- (void)runThread {@autoreleasepool {//返回runloop,可以让其他线程停止此线程self.currentRunloop = CFRunLoopGetCurrent();[self addSocketSource];CFRunLoopRun();}NSLog(@"线程退出");
}

//此方法在使用时没有多线程调用
- (void)stopThread {
	 [self removeSocketSource];
	 @synchronized (_currentRunloop) {if (_currentRunloop) {
	CFRunLoopStop(_currentRunloop);
	self.currentRunloop = NULL;
	}}
}

//此方法在使用时没有多线程调用
- (void)addSocketSource {int sock;sock = socket(AF_INET6, SOCK_STREAM, 0);CFSocketContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};self.socket = CFSocketCreateWithNative(NULL, sock, kCFSocketReadCallBack, socketCallBack, &context);self.socketSource = CFSocketCreateRunLoopSource(NULL, self.socket, 0);CFRunLoopAddSource(_currentRunloop, _socketSource, kCFRunLoopDefaultMode);
}

- (void)removeSocketSource {
	@synchronized (_socket) {
		if (_socket) {
			//CFSocketInvalidate可能被抛到另一个线程去执行,因此 CFSocketInvalidate 和 CFRunLoopStop可能有多线程同时调用的情况 
	CFSocketInvalidate(_socket);
	CFRelease(_socket);
	self.socket = NULL;
	}
	}
} 

在实践中,CFSocket是被另一个socket类管理的,所以addSocketSourceremoveSocketSource都是在另一个类中的,也就有可能出现CFSocketInvalidateCFRun

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值