How can I build a ThreadId given that I know the a

2019-02-23 16:23发布

It often happens to me when debugging or playing around in GHCi that I happen to know the actual ThreadId number (for example from using Debug.Trace), but that's all I have.

The problem is that all thread APIs, such as killThread require a ThreadId and not an Int.

I've tried Hoogle but came out empty. Is there a way to do this? I'm concerned mostly with debugging, so I don't mind if it's a nasty hack or if it's through a GHC-only library.

标签: haskell ghc ghci
1条回答
劳资没心,怎么记你
2楼-- · 2019-02-23 17:16

You can't. ThreadId is abstract. The Int you have is actually nothing more than a counter (source):

32  static StgThreadID next_thread_id = 1;
...
59  StgTSO *
60  createThread(Capability *cap, W_ size)
61  {
62      StgTSO *tso;
...
126     ACQUIRE_LOCK(&sched_mutex);
127     tso->id = next_thread_id++;  // while we have the mutex
...
130     RELEASE_LOCK(&sched_mutex);
...
136 }
...
161 int
162 rts_getThreadId(StgPtr tso) 
163 {
164   return ((StgTSO *)tso)->id;
165 }

It's rts_getThreadId that gets called in ThreadId's Show instance. There's no mapping back to the actual TSO. If you want to know what ThreadId belongs to what Int, you need to keep track of them yourself. You could, for example, parse the Int and fill a Map.

查看更多
登录 后发表回答