I don't use thread explicitly, so when designing an iPhone app, e.g. using Singleton, should I need to take care of the thread issue?
Beware of a singleton being called by or using any OS classes that could become multi-threaded on future multi-core hardware. Also beware of forgetting that this class isn't thread safe N years from now, reusing it, and wasting your life hunting the bug.
If not, no.
In the most part you should be safe, but I would be aware that even if you don't use threads explicitly, there are many libraries in the Apple SDK that have asynchronous callbacks (such as HTTP requests) where you will need to synchronize access across shared memory.
I hope this helps!
Related
Need your help.
In my application, i want to implement a background process which keeps running continuously and downloads the updated data and stores it in document folder.
And my main thread should keep checking the document folder and display the updated data in view control.
The child thread should end once the view disappears. and start again once the view appears.
What is the best way to do it? NSThread or NSOperationQueue? What precautions are required?
I also have to access few variables of the class. So is should be thread safe.
Thanks in advance.
Regards
If you do not need to update a progress bar or something in iOS5 there is one great API method + sendAsynchronousRequest:queue:completionHandler: that allows you to run async download as a block inside NSOperationQueue. If not you should look into third party libs such as ASIHTTP request or https://github.com/AFNetworking/AFNetworking(probably better the last one) or you need to build you own download manager, not a simple task
there are two ways to do it..
First: You use NSOperationQueue which is a bit bulkier as it is build on GCD but does have some extra features.
Second: You use GCD (grand central dispatch) looking at requirements I would say GCD seems fine as you can easily access any thread(main or background) this would be slightly quicker.
You can have a look at - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. In your viewDidDisappear, you can stop the task when your view disappears
From Apple Docs. Apple encourages to investigate the alternative Mac OS X technologies for implementing concurrency. This is especially true if you are not already familiar with the design techniques needed to implement a threaded application. These alternative technologies simplify the amount of work you have to do to implement concurrent paths of execution and offer much better performance than traditional threads.
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html#//apple_ref/doc/uid/10000057i-CH6-SW2
Whats the difference between detach and non-detach thread in iPhone?
The iPhone "Threading Programming Guide" documentation says that
By default the NSThread class creates detach threads
And it also says that a Detached thread means that the thread's resources are automatically reclaimed by system when the thread exits. In the same way , how does it happen in non-detach threads?
Thank You.
Suse
This relates to the underlying pthread implementation. Read up on pthread_detach and pthread_join to understand the differences.
In practice, you probably don't care and Cocoa/NSThread do the right thing for you automatically.
And to clarify, there's no way to create a non-detached thread using NSThread. You'd have to use the low-level thread API for that.
In Obj-C, what does it mean in simple terms;
"CoreData is not thread safe"
OR in general what is "not thread safe" ?
#d11wtq's answer is correct only when writing your own code or designing your own APIs.
It is entirely incorrect when working with a set of APIs and quite specifically wrong when working with Core Data.
In the context of working with Mac OS X and iOS, thread safety must always be considered in the context of working with the system APIs. Even using, say, an NSArray means that you are working with the system APIs.
OR in general what is "not thread
safe" ?
A non-thread safe API is an API where you cannot interact with the API from multiple threads simultaneously. There may also be additional restrictions that most often involve the main thread. For example, almost all drawing operations must occur on the main thread on both Mac OS X and iOS.
The Apple documentation assumes thread safety is the exceptional case. That is, an API is only thread safe if the documentation explicitly claims thread safety. If there is no mention of thread safety, you must assume that the API is not thread safe.
In Obj-C, what does it mean in simple
terms; "CoreData is not thread safe"
That statement is not quite correct, but it is a safe assumption.
In Core Data's case, the thread interaction behavior is extremely well documented.
In short, parts of the API are thread safe (the store coordinator, for example) and parts are quite explicitly not thread safe. While the MOC provides lock and unlock methods, you can also use external locking. But don't. It will be less efficient and more fragile; significantly so. In general, don't use the internal locking either. CoreData is optimized around having a context per thread/queue.
(Answer fixed based on TC's feedback. Thanks.)
UPDATE | Please see #bbum's answer. I accept that my answer is flawed and #bbum is correct.
If something is described as "not thread safe", it means that no special precautions have been taken to ensure it won't crash should two separate threads try to use it simultaneously. In general, code that is to be used by more than one thread requires explicit locks (or #synchronize blocks) wrapping around aspects of the code. In particular, any object/variable that will be modified would almost certainly cause a crash if two threads happened to write to it at the same time (since they'd be writing to the same memory address). Similarly, if one thread was reading a variable while another was writing to it, garbage would be returned and the program would likely crash.
Using #synchronized, or NSLock or a POSIX mutex etc, ensures that only one thread can execute a particular block of code at any given time. The other threads get blocked and have to wait until the lock is released. There is a slight performance hit with using locks (and of course some development overhead having to think about them), so often code expressly declares that it is not thread safe, leaving you, the adopter of the code, to place locks as needed yourself (or limit execution of the non thread-safe to a single thread).
See the Apple documentation for more information about threading and thread safety:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocThreading.html#//apple_ref/doc/uid/TP30001163-CH19-BCIIGGHG
I tried it, but I think this notification isn't coming. Is that the normal case?
No, this notification is sent by NSThread. If you're using ordinary pthreads, it won't be sent.
From the docs:
Protecting the Cocoa Frameworks For
multithreaded applications, Cocoa
frameworks use locks and other forms
of internal synchronization to ensure
they behave correctly. To prevent
these locks from degrading performance
in the single-threaded case, however,
Cocoa does not create them until the
application spawns its first new
thread using the NSThread class. If
you spawn threads using only POSIX
thread routines, Cocoa does not
receive the notifications it needs to
know that your application is now
multithreaded. When that happens,
operations involving the Cocoa
frameworks may destabilize or crash
your application.
To let Cocoa know that you intend to
use multiple threads, all you have to
do is spawn a single thread using the
NSThread class and let that thread
immediately exit. Your thread entry
point need not do anything. Just the
act of spawning a thread using
NSThread is enough to ensure that the
locks needed by the Cocoa frameworks
are put in place.
If you are not sure if Cocoa thinks
your application is multithreaded or
not, you can use the isMultiThreaded
method of NSThread to check.
It should also be noted that 'times have changed' since NSWillBecomeMultiThreadedNotification was added to Foundation. Multi-threaded programming is now much, much more common. It's now entirely within the realm of possibility, even likely, that you'll never see this notification posted in an app. Modern apps become multi-threaded very early in their life, possibly before any part of your code is ever executed. Also from the documentation:
If you are developing a Cocoa library,
you can register as an observer for
the
NSWillBecomeMultiThreadedNotification
if you want to be notified when the
application becomes multithreaded. You
should not rely on receiving this
notification, though, as it might be
dispatched before your library code is
ever called.
I'd use [NSThread isMultiThreaded] instead of relying on NSWillBecomeMultiThreadedNotification.
I have an application that opens a connection with 2 sockets (in and out) and I want to have them working in a thread.
The reason that I want them to be in a separate thread is that I don't want my application to freeze when I receive data, and this can happen anytime as long as the application is running.
Currently I have a class that handle also network communication and I run this class in an NSOperation, I'm not sure if it's the best solution.
I'm not very familiar with threading so guys if you could give me some help I would be very grateful.
Thanks
First, you should know that you can use the same socket to send and receive data — they're generally bi-directional. You should be able to share a reference to the same socket among multiple threads of execution.
Second, unless you'll be receiving large amounts of data and have experienced performance issues with your UI, I would delay optimizing for it. (Don't get me wrong, this is a good consideration, but premature optimization is the root of all evil, and simpler is generally better if it performs adequately.)
Third, NSOperation objects are "single-shot", meaning that once the main method completes, the operation task cannot be used again. This may or may not be conducive to your networking model. You might also look at NSThread. The fact that you already have the functionality "factored out" bodes well for your design, whatever turns out to be best.
Lastly, threading is a complex topic, but a good place to start (especially for Objective-C) is Apple's Threading Programming Guide.