I'm making an iPhone app using threads.
I was used C# for a while, there was a method Thread.Join() which blocks current thread for specific thread completes execution. What's the equivalent in Cocoa for it? Or Alternatives?
---edit---
PS. I'm using NSThread.
---edit---
I'm finding a method like 'waitForThreadExit' which blocks caller thread until thread completes execution.
The threads created with Cocoa cannot be created as detached. NSThread instances always wrap attached POSIX threads for resource management reasons. As quoted in the Thread Programming Guide:
If you do want to create joinable
threads, the only way to do so is
using POSIX threads. POSIX creates
threads as joinable by default. To
mark a thread as detached or joinable,
modify the thread attributes using the
pthread_attr_setdetachstate function
prior to creating the thread. After
the thread begins, you can change a
joinable thread to a detached thread
by calling the pthread_detach
function. For more information about
these POSIX thread functions, see the
pthread man page. For information on
how to join with a thread, see the
pthread_join man page.
If you are looking for a way to be notified of the end of a NSThread, you can use the NSThreadWillExitNotification notification.
NSThread does not expose a Join method by any name. NSThread is a very simple, high level, wrapper class. It's very useful for doing threading in a GUI app as it simplifies calling back onto the main thread. For simple backgrounding of tasks and communicating the result back to the main thread on completion this should be sufficient and is fairly easy to get right. If you want to do more "advanced" things (and that includes Join, here) then you'll either have to go to pthreads or layer the semantics on top of NSThread (perhaps by using NSCondition).
If you are using pthreads, then use: pthread_join.
On the other hand, if you are using NSThread class, there is no equivalent to join method you are referring to.
You could try wiht NSObject's message performSelectorOnMainThread:withObject:waitUntilDone:
But I am not exactly sure what you are trying to accomplish here.
Here's is Apple's Multithreading Programming Guide.
You can do this yourself using NSConditionLock. Define two conditions: "running" and "terminated". The worker thread acquires the lock "running" and upon termination it unlocks with condition "terminated". A join would then be to acquire the lock "terminated" and then unlock it "terminated".
Related
I want to perform some load and save operations on another thread (in SDL). To be able to do this I thought of creating a thread and detaching it (letting it end on its own) everytime I call a function that needs to run separately.
But I don't think this is the correct behaviour (or is it?).
Is there any better solution, like creating and using only one thread? And if there is, how can I call my function(s) from it?
Use std::async. On most implementations it uses efficient solutions like reusing threads from threadpool.
The Life span of a thread is dependent on the main thread(or parent thread), without a join all children threads would be terminated when the main thread(or parent thread) exit.A thread is tied to the process. You might want to looking into forking a process instead, this would persist even if the parent process exit, but would be could be come a zombie process, with no way of terminating it within the program.
Can a Windows thread suspend itself with SuspendThread()?
I can awake it from another one but, can it call SuspendThread(GetCurrentThreadId())?
It seems this is possible, but with a slight alteration (see the cygwin mailing list discussing this here):
SuspendThread(GetCurrentThread());
I also found MSDN saying a thread should only suspend itself, but it doesn't make it clear for me. I quote (from here, emphasis mine):
This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.
Yes, you can use SuspendThread on current thread. Good read on the topic.
As a method of creating reusable threads for work tasks without the overhead of create and terminate tasks, suspend and resume thread could be used to quiesce a thread at the end of the task. When work is dispatch to the thread, resume it.
what i s the difference between SetEvent() and Thread Lock() function? anyone please help me
Events are used when you want to start/continue processing once a certain task is completed i.e. you want to wait until that event occurs. Other threads can inform the waiting thread about the completion of this task using SetEvent.
On the other hand, critical section is used when you want only one thread to execute a block of code at a time i.e. you want a set of instructions to be executed by one thread without any other thread changing the state at that time. For example, you are inserting an item into a linked list which involves multiple steps, at that time you don't want another thread to come and try to insert one more object into the list. So you block the other thread until first one finishes using critical sections.
Events can be used for inter-process communication, ie synchronising activity amongst different processes. They are typically used for 'signalling' the occurrence of an activity (e.g. file write has finished). More information on events:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686915%28v=vs.85%29.aspx
Critical sections can only be used within a process for synchronizing threads and use a basic lock/unlock concept. They are typically used to protect a resource from multi-threaded access (e.g. a variable). They are very cheap (in CPU terms) to use. The inter-process variant is called a Mutex in Windows. More info:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682530%28v=vs.85%29.aspx
The main program is creating a child thread. The child thread is running a loop and this thread needs to be paused and resumed based on events taking place in main thread.
What would the best way to accomplish this? IPC?
Communication between thread should be done using thread safe classes.
You can use Queue since it as a blocking method: pop.
If you want a more specific response you need to provide more details about your use case.
Yesterday I read somewhere that NSTask isn't thread safe and that bothers me a lot, because I'm running a NSTask within a NSThread and is so far not experiencing any threading issues with it.
My code is organized like this
A: main thread -> B: worker thread -> C: worker task
C: The worker task is a commandline program.
B: The worker thread can start/stop the worker task and send it commands.
A: The main thread can send commands to the worker thread.
If NSTask is supposed to be used only within the main thread, then I'm considering moving the NSTask start/stop code to the main thread, just to prevent possible threading issues.
Can NSTask be used outside the main thread?
And if not then what may be the threading issues with NSTask?
I read somewhere that NSTask isn't thread safe…
That's not what that page says. It says that you'll get the process-terminated notification on the same thread you launched it from, which suggests that NSTask is aware of threads and tries to do the right thing.
The problem one of the editors of that page encountered was that they started their process from a thread, then let the thread die. That caused a crash because the framework was no longer able to deliver the process-terminated notification to the correct thread.
The Thread Safety Summary (bookmark that) says something similar, listing NSTask in a list of classes about which it says:
In most cases, you can use these classes from any thread as long as you use them from only one thread at a time. Check the class documentation for additional details.
The NSTask documentation doesn't say anything additional about threads, so it sounds like NSTask is one of the “most cases”: You can use a task from the thread you created it on. Don't use the same task on another thread, and (as noted above) make sure the thread lasts at least as long as the task process.
I will note, however, that in most cases, there is no need to run a task on a separate thread. Separate processes tend to run on other processors just as other threads in your process do, and the run loop does a good job of multiplexing many small events and keeping the UI responsive. You can use NSFileHandle's readInBackgroundAndNotify method if you need to read output from the task. You may be able to cut out your worker threads entirely.
The alternative is, as Eimantas suggested, to use NSOperation: Have an operation that simply starts a particular task and waits for that task to exit (perhaps synchronously reading output from it). The operation is complete when the task has exited.
Yes, it can, but I suggest you using NSOperation. It's KVO-agnostic (unlike threaded NSTask). Also you may want to look into receptionist design pattern regarding KVO and threaded environment (in case you need KVO).