Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build a ThreadId given that I know the actual number?

Tags:

haskell

ghc

ghci

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.

like image 890
Jakub Arnold Avatar asked Jul 28 '14 12:07

Jakub Arnold


People also ask

How do I get Threadid?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads.

How do I get Threadid in C++?

Thread get_id() function in C++ Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.

How do I know how many threads I have used?

Open Task Manager (press Ctrl+Shift+Esc) Select Performance tab. Look for Cores and Logical Processors (Threads)

How do I create a Pthread?

pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier. The thread is created running start_routine, with arg as the only argument.


1 Answers

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.

like image 109
Zeta Avatar answered Oct 01 '22 13:10

Zeta