Ruby - Control child threads from main thread - ruby

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.

Related

How to call a function inside a thread?

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.

Is it possible to share the same message queue between two threads?

What I would like to do is to have one thread waiting for messages (WaitMessage) and another processing the logic of the application. The first thread would wake up on every message, signal somehow this event to the other thread, go to sleep again, etc. Is this possible?
UPDATE
Consider the following situation. We have a GUI thread, and this thread is busy in a long calculation. If there is no other thread, there is no option but to check for new messages from time to time. Otherwise, the GUI would become irresponsive during the long calculation. Right now my system uses this "polling" approach (it has a single thread that checks the message queue from time to time.) However, I would like to know whether this other solution is possible: Have another thread waiting on the OS message queue of the GUI so that when a Windows message arrives this thread will wake up and tell the other about the message. Note that I'm not asking how to communicate the news between threads but whether it is possible for the second thread to wait for OS messages that arrive in the queue of the first thread.
I should also add that I cannot have two different threads, one for the GUI and another for the calculations, because the system I'm working on is a Virtual Machine on top of which runs a Smalltalk image that is not thread safe. That's why having a thread that only signals new OS messages would be the ideal solution (if possible.)
This depends on what the second thread needs to do once the first thread has received a message.
If the second thread simply needs to know the first thread received a message, the first thread could signal an Event object using SetEvent() or PulseEvent(), and the second thread could wait on that event using WaitForSingleObject().
If the second thread needs data from the first thread, it could use an I/O Completion Port. The first thread could wrap the data inside a dynamically allocated struct and post it to the port using PostQueuedCompletionStatus(), and the second thread could wait for the data using GetQueuedCompletionStatus() and then free it when done using it.
Update: based on new information you have provided, it is not possible for one thread to wait on or service another thread's message queue. Only the thread that created and owns the queue can poll messages from its queue. Each thread has its own message queue.
You really need to move your long calculations to a different thread, they don't belong in the GUI thread to begin with. Let the GUI thread manage the GUI and service messages, do any long-running things in another thread.
If you can't do that because your chosen library is not thread safe, then you have 4 options:
find a different library that is thread safe.
have the calculations poll the message queue periodically when running in the GUI thread.
break up the calculations into small chunks that can be triggered by the GUI thread posting messages to itself. Post a message and return to the message loop. When the message is received, do a little bit of work, post the next message, and return to the message loop. Repeat as needed until the work is done. This allows the GUI thread to continue servicing the message queue in between each calculation step.
move the library to a separate process that communicates back with your main app as needed.

Mutex vs Event in Windows

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.

What's the equivalent C# 'Thread.Join()' in Cocoa?

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".

Why use ReadDirectoryChangesW asynchronously?

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.

Resources