开发者

Cocoa/Objective C: methods and thread safety

In Cocoa/Objective C, are static class methods thread safe ? I am defining a class to make related custom URL requests, that I would like to call from many different threads. Let's say I have a class:

@interface URLConnector : NSObject {
}
+(Response *)getData:(NSString *)category;
+(Response *)put:(NSString *)category content:(NSData *)content;
@end

Each method defines an NSMutableURLRequest, calls it, and uses NSRunLoop:runUntilDate: to wait for the response. They also create instances of another class, URLConnectorDelegate to handle the callbacks from the NSMutableRequests, and release them before returning. (note: this code is based on a popular public library for making URL requests)

What I like about this approach is that it keeps all the threads simple and puts all the custom server-related code in one place. The threads can execute URL requests with a single function call.

Can all of my threads use the开发者_StackOverflow社区se static functions at once to make simultaneous calls (i.e. are static objective-c methods inherently thread-safe) ?


Being a class method has no influence one way or another on thread safety. What matters is how you access data. If you access data in ways that are not thread-safe, the method isn't thread-safe.

Rather than pumping your own run loop, I'd just attach the NSURLConnection to the main run loop and the URL loading system manage itself like it's designed to. See NSURLConnection scheduleInRunLoop:forMode:


If you know you are going to be on a background thread why not just use +[NSURLConnection sendSynchronousRequest:returningResponse:error:] and be done with it?

No fuzz with the run-loop needed. And if you only use local variables and the arguments you get thread safety with barely any work at all.

Otherwise thread safety is up to you independently of method type.

Class methods are not any bit more thread safe than instance methods. Both kinds of methods are in fact treaded just the same by the run-time. The class is actually an object instance of it's meta-class, so a call to a class method is a normal method call to an object.


I don't see any way you can do all the processing in the class methods without using instance variables that can get stomped on from various threads. I think you need to make those methods normal instance methods and allocate an instance for each thread. I'm not sure why you would even consider making them class methods in the first place.


Assuming you are calling NSRunLoop:runUntilDate: for the current thread's run loop (i.e. whichever thread calls your class method), if there's no global/static variable being modified in these class methods, I believe they should be thread safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜