views:

177

answers:

3

In a multi-thread app. is there a way to programatically have thread-B check what function thead-A is currently in?

+5  A: 

You can get a stack trace of another thread by doing this:

System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(myThread);

From this you can get the call stack, and the function it's currently executing.

Jon Tackabury
It's worth noting that I don't know if there are any threading issues you may encounter by doing this.
Jon Tackabury
The other SO question says Suspend/Resume needs to be called.
MichaelGG
A: 

This is something that should be built in to the application itself in order to avoid possible contention between threads.

In my opinion, a thread should never control the execution of another (e.g., suspend/resume), except for starting it. They should merely suggest that the other thread control itself (with mutexes and events, for example). That greatly simplifies thread management and reduces the possibility of race conditions.

If you really want thread B to know what thread A is currently doing, thread A should be communicating that to thread B (or any other thread such as the main thread below) using, as an example, a mutex-protected string with the function name in it. Something along the lines of (pseudo-code):

global string threadAFunc = ""
global mutex mutexA
global boolean stopA

function main:
    stopA = false
    init mutexA
    start threadA
    do until 20 minutes have passed:
        claim mutexA
        print "Thread A currently in " + threadAFunc
        release mutexA
    stopA = true
    join threadA
    return

 

function threadA:
    string oldThreadAFunc = threadAFunc
    claim mutexA
    threadAFunc = "threadA"
    release mutexA

    while not stopA:
        threadASub

    claim mutexA
    threadAFunc = oldThreadAFunc
    release mutexA
    return

function threadASub:
    string oldThreadAFunc = threadAFunc
    claim mutexA
    threadAFunc = "threadASub"
    release mutexA

    // Do something here.

    claim mutexA
    threadAFunc = oldThreadAFunc
    release mutexA
    return

This method can be used in any language or environment that supports threading, not just .Net or C#. Each function in thread A has prolog and epilog code to save, set and restore the values used in other threads.

paxdiablo