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.
Related
Is the thread in MS Windows with C++ a time slice or the execution of a function or both?
A thread is executing a function which is a block of code inside an outer loop. If you send a signal (via a global variable) to break from the outer loop. The function returns, but what happens to the running thread assuming it is a time slice of execution?
Neither.
If your scheduler is set to a time-slice algorithm then the time-slice represents when and how long your thread will run.
A thread is an object that manages a block of executable code that can be scheduled. Typically, as part of thread creation you pass a function pointer to that block of code. When the "job" of the executable code is done the thread is destroyed.
In 32-bit and 64-bit Windows, every thread runs a specified function. Conceptually speaking, the initial thread of a new process runs the application's main function, and every additional thread runs a function specified by the programmer when the thread is created. See the documentation for CreateThread; the lpStartAddress argument specifies the function for the thread to run.
(In fact, each thread also runs operating system code, and usually runtime library code as well, but that's an implementation detail that doesn't matter for our purposes.)
Conceptually, when any particular thread is running on a particular CPU core, it might stop for either of two reasons: because the thread has stopped running altogether, or because of a context switch. In the case of a context switch, the thread will be started up again at a later time, and from the thread's point of view everything will look the same as it did when it was interrupted.
(In fact, the OS may also interrupt the thread in order to run device driver or other operating system code. This doesn't involve a context switch; the device driver code runs in the context of the interrupted thread, which is one of the reasons device drivers are hard to write.)
Here are some of the reasons the thread might stop running altogether ["exit"]:
The function the thread was created to run has exited.
The thread calls ExitThread().
Some other thread calls TerminateThread().
Here are some of the reasons there might be a context switch:
The thread's timeslice has expired.
Another thread with a higher priority has become ready to run.
The thread calls Sleep() or one of the wait functions.
It's hard to tell what you're trying to ask, so this may not have addressed it. But perhaps it will clarify things enough to allow you to ask your question in words I can understand.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686289%28v=vs.85%29.aspx
According to msdn, in the remarks sections, it states:
"If the thread that set the timer terminates and there is an associated completion routine, the timer is canceled. However, the state of the timer remains unchanged. If there is no completion routine, then terminating the thread has no effect on the timer."
Then further down, it states:
"If the thread that called SetWaitableTimer exits, the timer is canceled. This stops the timer before it can be set to the signaled state and cancels outstanding APCs; it does not change the signaled state of the timer."
Hence my question,
if I have one thread calling SetWaitableTimer without an associated completion routine and another thread calling WaitOnMultipleObjects(passing in the timer object handle) and the thread that calls SetWaitiableTmer exits shortly thereafter, would the timer object be cancelled or would it still become signaled when the period expires?
To give more information directly from the implementation of waitable timers: if you use a CompletionRoutine, the timer is placed on a linked list chained off the thread which called SetWaitableTimer. When the thread is terminated, the kernel walks the dying thread's linked list and cancels are timers which are still queued.
If you're not using a completion routine, the timer is never added to any thread's linked list and thus isn't cancelled when any particular thread dies.
The documentation is somewhat unclear. I think the best you can do is test it yourself. I believe however that the timer cancels automatically only if the I/O completion routine is used.
I can give some "theoretical" background about windows APCs, to justify my (educated) guess.
APC = "asynchronous procedure call". In windows every user-mode thread is equipped with a so-called APC queue, a system-managed queue of procedures that must be called on this thread. A thread may enter a so-called "alertable wait" state (on purpose), during which it may execute one or more of the procedures in this queue. You may either put the procedure call in the APC queue manually, or issue an I/O, which on completion will "put" the procedure call there.
In simple words the scenario is the following: you issue several I/Os, and then you wait for either of them to complete (or fail), and, perhaps, some other events. You then call one of the alertable-waiting functions: SleepEx, WaitForMultipleObjectsEx or similar.
Important note: this mechanism is designed to support a single-threaded concurrency. That is, the same thread issues several I/Os, waits for something to happen, and responds appropriately. All the APC routines are guaranteed to be called in the same thread. Hence - if this thread exits - there's no way to call them. Hence - all the outstanding I/Os are also cancelled.
There are several Windows API functions that deal with asynchronous I/O, whereas they allow a choice of several completion mechanisms (such as ReadFileEx): APC, setting an event, or putting a completion in the I/O completion port. If those functions are used with APC - they automatically cancel the I/O if the issuing thread exits.
Hence, I guess that waitable timer auto-cancels only if used with APC.
can somebody please explain what is the difference if I do
mutex = createMutex
waitForSingleObject
Release(mutex)
and
event = createEvent
waitForSingleObject
Release(event)
I'm so confused, can I use both versions for the synchronization? thanks in advance for any help
You use a mutex to ensure that only one thread of execution can be accessing something. For example, if you want to update a list that can potentially be used by multiple threads, you'd use a mutex:
acquire mutex
update list
release mutex
With a mutex, only one thread at a time can be executing the "update list".
You use a manual reset event if you want multiple threads to wait for something to happen before continuing. For example, you started multiple threads, but they're all paused waiting for some other event before they can continue. Once that event happens, all of the threads can start running.
The main thread would look like this:
create event, initial value false (not signaled)
start threads
do some other initialization
signal event
Each thread's code would be:
do thread initialization
wait for event to be signaled
do thread processing
Yes, both can be used for synchronization but in different ways.
Mutex is a mutual exclusion object and can be acquired only by a single instance at a time. It is used to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code
Event is an objet that can be explicitly set to a state by use of the SetEvent function.
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".
I've read the documentation for ReadDirectoryChangesW() and also seen the CDirectoryChangeWatcher project, but neither say why one would want to call it asynchronously. I understand that the current thread will not block, but, at least for the CDirectoryChangeWatcher code that uses a completion port, when it calls GetQueuedCompletionStatus(), that thread blocks anyway (if there are no changes).
So if I call ReadDirectoryChangesW() synchronously in a separate thread in the first place that I don't care if it blocks, why would I ever want to call ReadDirectoryChangesW() asynchronously?
When you call it asynchronously, you have more control over which thread does the waiting. It also allows you to have a single thread wait for multiple things, such as a directory change, an event, and a message. Finally, even if you're doing the waiting in the same thread that set up the watch in the first place, it gives you control over how long you're willing to wait. GetQueuedCompletionStatus has a timeout parameter that ReadDirectoryChangesW doesn't offer by itself.
You would call ReadDirectoryChangesW such that it returns its results asynchronously if you ever needed the calling thread to not block. A tautology, but the truth.
Candidates for such threads: the UI thread & any thread that is solely responsible for servicing a number of resources (Sockets, any sort of IPC, independent files, etc.).
Not being familiar with the project, I'd guess the CDirectoryChangeWatcher doesn't care if its worker thread blocks. Generally, that's the nature of worker threads.
I tried using ReadDirectoryChanges in a worker thread synchronously, and guess what, it blocked so that the thread wouldn't exit by itself at the program exit.
So if you don't want to use evil things like TerminateThread, you should use asynchronous calls.