如果你还不了解什么是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类管理的,所以addSocketSource
和removeSocketSource
都是在另一个类中的,也就有可能出现CFSocketInvalidate
和 CFRun