代码之家  ›  专栏  ›  技术社区  ›  Dacto

功能意识?

  •  4
  • Dacto  · 技术社区  · 16 年前

    在多线程应用程序中。有没有办法用编程的方式让thread-B检查ead-a当前使用的函数?

    2 回复  |  直到 16 年前
        1
  •  5
  •   Apocalisp    16 年前

    执行以下操作可以获取另一个线程的堆栈跟踪:

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

    从这里可以得到调用堆栈,以及它当前正在执行的函数。

        2
  •  0
  •   paxdiablo    16 年前

    为了避免线程之间可能发生的争用,应该在应用程序本身中内置这种东西。

    在我看来,线程不应该控制另一个线程的执行(例如suspend/resume),除非启动它。它们应该只是建议另一个线程控件 它本身 (例如,使用互斥锁和事件)。这大大简化了线程管理并减少了争用条件的可能性。

    如果您真的想让线程B知道线程A当前正在做什么,那么线程A应该使用一个带有函数名的互斥保护字符串作为示例,将其与线程B(或任何其他线程,如下面的主线程)进行通信。类似于(伪代码)的东西:

    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
    

    此方法可用于 任何 支持线程的语言或环境,而不仅仅是.Net或C#。线程A中的每个函数都有prolog和epilog代码来保存、设置和恢复其他线程中使用的值。