What happens if dispatch_main gets called from outside of the main thread? - macos

The dispatch_main function is used to make the main thread start processing blocks dispatched to the main queue. So, dispatch_main is a kind of run loop, which doesn't return and, after processing the already-queued blocks, waits for other blocks to be submitted to the main queue.
So, what happens if dispatch_main gets called from outside of the main thread? If the main thread is processing another function, is it interrupted in order to allow the main thread to process the queued blocks? Is it allowed to call dispatch_main from outside of the main thread?

dispatch_main() asserts when called from outside of the main thread and aborts your process, it must only be called from the main thread.
dispatch_main() is really nothing other than pthread_exit() in disguise (see implementation): it turns the main queue into an ordinary serial dispatch queue and then terminates the main thread.
The main queue will be serviced by an on-demand workqueue thread from that point on, just like any other dispatch queue.

Related

Calling complete() on automatic variable of type struct completion defined in "waiting" thread

I try to understand use of completion in a piece of code.
Basically, one kernel thread creates automatic variable struct completion which is, I assume, allocated on the thread's stack. Then it pushes pointer of the completion struct to another thread (using fifo) and waits for completion.
struct completion done;
init_completion(&done);
push_to_fifo(&done);
wait_for_completion(&done);
The second thread fetches request from fifo, processes it and completes task.
Will the done variable be accessible from the second thread which calls complete(done)?
The first thread is waiting for the second to finish, so the struct completion on its stack will be stable until after wait_for_completion returns.
The stack space where that structure resides is just regular memory, the same as heap-allocated memory. The only difference is that once this function returns, and its caller invokes a different function, the same memory gets re-used for the stack frame / local variables of that next function.
So, if the other thread were to access the structure after that point, that would be a problem, but the point is that is supposed to be finished by then and once it signals "done", it shouldn't touch that memory again.

Who is the calling thread of the callback function set by CreateTimerQueueTimer()?

I guess it's the thread, say A, on which the timer was created. But I can't figure out how exactly the callback function is called. Assume the timer expires, and then what happens? Does this happen when this thread gets its time slice? And if this is the case, I think the function should be called by the scheduler or what before the context is finally switched to A, then can I say A is the caller?
Thanks.
The timer callback can also be called by a pool thread, a thread that specifically manages timers or in the context of the creating thread, (the creating thread is designed to accept and process an 'Asynchronous Procedure Call'). The flag paramters in CTQT() control the action upon timer expiry.
If the timer event is called by a pool thread or timer-manager thread, that thread will become ready upon expiry and, when there is a core available to run it, it will make the callback 'immediately' within its own context. The thread that created the timer could, if it wished, wait on a synchro object, (event or semaphore), that could be signaled by the timer callback, (ie. normal inter-thread comms).
The timer callback can only be executed in the context of the thread that created it if that thread is in a position to execute the callback when it receives some sort of signal. In the case of these timers, an APC is QUEUED to the creating thread and, if that thread is blocked on one of the 'alertable' wait calls, it will become ready immediately, will run when there is a core available to run it. After the APC has run, the wait call will return. If the wait call is not SleepEx(), it will return WAIT_IO_COMPLETION - a result that is usually ignored. If the thread is not waiting when the APC is queued up, it will not be executed until the thread makes the next wait call, (obviously - since the thread must be off doing something else:).
'And if this is the case, I think the function should be called by the scheduler or what before the context is finally switched to A, then can I say A is the caller?' NO!

Which thread will run a method of a TThread instance? (In Wait mode)

When a TThread enters in Synchronized() method, it waits until EnterCriticalSection(ThreadLock) returns.
Now, which one will run the method if in the meantime, another Tthread, or even the main thread call some method of the waiting Tthread?
What could happen if in the meantime, another thread, or even the main thread call some method of the waiting thread?
Threads do not have methods, so this question is a non-sequitur.
It is not meaningful to ask what happens when you call a method of another thread. Because it is not possible to do so. When you call a method, that method executes on thread which called it.
A method like TThread.Synchronize schedules the execution of code onto a different thread. But, the body of TThread.Synchronize is executed by the thread of the caller.
A call to EnterCriticalSection cannot be interrupted by user mode code. So, suppose that thread A calls EnterCriticalSection at a point where thread B holds the lock. The call to EnterCriticalSection made on thread A will not return until thread B has released the lock. While thread A is blocked waiting to acquire the lock, no code will execute on thread A.
It seems, from clarifications in the comments, that your question is in fact:
When a method of TThread is called, on which thread does that method execute?
The answer is that the method is executed on the calling thread. There's nothing special about the TThread class and so the normal rules apply.

When a thread that calls SetWaitableTimer exits while another thread is waiting on the timer, is the timer cancelled?

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.

Ruby - Control child threads from main thread

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.

Resources