how to set information on a thread context using ASM? - bytecode

Each time a new thread is being created / picked out of a threadpool, I want to be able to set some context information about it.
I'll appreciate for guidelines about what is the best approach to do it using ASM.
Thanks,
Nadav

This requires you to instrument the methods that start a thread or that is traversed when a thread pool triggers a new task. This makes this straigt forward:
You can instrument the Thread::start method for setting such a value for a Thread.
You can instrument the ThreadPoolExecutor::beforeExecute method to set a Thread state for a ThreadPoolExecutor. It is not possible to do this for generic Executors as they do not necessarily need to be backed by a Thread.

Related

Where is a thread's context saved and can it be accessed programmatically (without modifying the kernel)?

Windows Context Switching
The scheduler maintains a queue of executable threads for each
priority level. These are known as ready threads. When a processor
becomes available, the system performs a context switch. The steps in
a context switch are:
Save the context of the thread that just finished executing.
Place the thread that just finished executing at the end of the queue for its priority.
Find the highest priority queue that contains ready threads.
Remove the thread at the head of the queue, load its context, and execute it.
I don't know much about the topic yet, so I don't know how to elaborate on my question. Where is a thread's context saved, and can it be accessed (edit: read) programmatically (without modifying the kernel)?
If you have a handle to a thread with the required access rights you can suspend the thread and then call GetThreadContext. When a thread is running the values are in the real CPU registers, when it is not running the context is stored in memory not accessible from usermode.
The context stores the values of various CPU registers, it is only useful to debuggers and advanced features like code injection and error logging.

creating delphi timers dynamically at runtime (performance, cpu consuming)

In my current project I have a structure like this:
Main Thread (GUI):
->Parser Thread
->Healer Thread
->Scripts Thread
the problem is that the Healer & Scripts Threads have to create childthreads with their appropiate timer, it would look like this:
->Parser Thread
->Healer Thread:
-->Healer 1
-->Healer 2
--> (...)
->Scripts Thread:
-->Script 1
--> (...)
For doing this I have thought about coding a dynamically Timer which would be created at runtime when a new Heal/Script is added.
Now the problem/question is:
maybe I have like 20 timers runing at the same time because of this, wouldn't this be a problem to my program performance (CPU consuming, etc)?
Is this the best way to achieve what I'm looking for?
Thanks in advance
There's no problem with having up to 20 timers active at one time in an application. Modern hardware is more than capable of handling that.
Remember also that timer messages are low priority messages and so are only synthesised when the message queue is empty. So, you need to keep the message queues of your threads serviced promptly in order for the messages to be delivered in a timely manner.
A bigger problem for you is that you cannot create TTimer instances outside the GUI/VCL thread. That's because the timer component calls AllocateHWnd which is not thread safe and can only be called from the GUI/VCL thread. So, you'll need to interact with the raw Win32 timer API directly and not use the VCL TTimer wrapper.

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.

Forcing context switch in Windows

Is there a way to force a context switch in C++ to a specific thread, assuming I have the thread handle or thread ID?
No, you won't be able to force operating system to run the thread you want. You can use yield to force a context switch though...
yield in Win32 API is function SwitchToThread. If there is no other thread available for running, then a ZERO value will be returned and current thread will keep running anyway.
You can only encourage the Windows thread scheduler to pick a certain thread, you can't force it. You do so first by making the thread block on a synchronization object and signaling it. Secondary by bumping up its priority.
Explicit context switching is supported, you'll have to use fibers. Review SwitchToFiber(). A fiber is not a thread by a long shot, it is similar to a co-routine of old. Fibers' heyday has come and gone, they are not competitive with threads anymore. They have very crappy cpu cache locality and cannot take advantage of multiple cores.
The only way to force a particular thread to run is by using process/thread affinity, but I can't imagine ever having a problem for which this was a reasonable solution.
The only way to force a context switch is to force a thread onto a different processor using affinity.
In other words, what you are trying to do isn't really viable.
Calling SwitchToThread() will result in a context switch if there is another thread ready to run that are eligible to run on this processor. The documentation states it as follows:
If calling the SwitchToThread function
causes the operating system to switch
execution to another thread, the
return value is nonzero.
If there are no other threads ready to
execute, the operating system does not
switch execution to another thread,
and the return value is zero.
You can temporarily bump the priority of the other thread, while looping with Sleep(0) calls: this passes control to other threads. Suppose that the other thread has increased a lock variable and you need to wait until it becomes zero again:
// Wait until other thread releases lock
SetThreadPriority(otherThread, THREAD_PRIORITY_HIGHER);
while (InterlockedRead(&lock) != 0)
Sleep(0);
SetThreadPriority(otherThread, THREAD_PRIORITY_NORMAL);
I would check out the book Concurrent Programming for Windows. The scheduler seems to do a few things worth noting.
Sleep(0) only yields to higher priority threads (or possibly others at the same priority). This means you cannot fix priority inversion situations with just a Sleep(0), where other lower priority threads need to run. You must use SwitchToThread, Sleep a non-zero duration, or fully block on some kernel HANDLE.
You can create two synchronization objects (such as two events) and use the API SignalObjectAndWait.
If the hObjectToWaitOn is non-signaled and your other thread is waiting on the hObjectToSignal, the OS can theoretically perform quick context switch inside this API, before end of time slice.
And if you want the current thread to automatically resume, simply inform a small value (such as 50 or 100) on the dwMilliseconds.

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

Resources