SimonC
SimonC

Reputation: 1618

Output thread IDs as seen by debugger

I'm developing a multi-threaded C++ application using GCC 4.4.5 and GDB 7.2. At the moment, I have four threads. Each one interacts with a CAN bus in one form or another, either reading, writing, polling or handling messages.

In order to determine which thread is doing what, I have decided to add the thread IDs to log messages. In my logging functions, I have the following code:

// This is for outputting debug messages
void logDebug(string msg, thread::id threadId[ = NULL]) {
    #ifdebug _DEBUG
    threadState.outputLock->lock();
    if (threadId != NULL)
        cout << "[Thread #" << threadId << "] ";
    // The rest of the output
    threadState.outputLock->unlock();
    #endif
}

This is the (debug) output from the application:

[Thread #3085296768] [DEBUG] [Mon Jun 17 10:18:45 2019] CAN frame was empty or no message on bus...
         ----------

And this is the what GDB is telling me:

Thread #3 7575 [core: 0] (Suspended: Breakpoint)
          ----

Why is the debugger giving me different information from the application (the thread IDs/numbers) and is there a way to output the same information in the application, as the debugger is telling me?

The expected behaviour is that the thread IDs are identical.

EDIT: I forgot to add some possibly important information. I'm cross-compiling to an embedded device powered by a POWERPC chip, running a derivative of Debian Wheezy.

Upvotes: 3

Views: 1363

Answers (1)

kzsnyk
kzsnyk

Reputation: 2211

You can get the thread id from your application with the following system call : syscall(SYS_gettid)

From there you can set the thread name by either :

  • writing directly the name in /proc/PID/task/TID/comm
  • using the pthread function int pthread_setname_np(pthread_t thread, const char *name)

Then in GDB you can easily match the given thread name, its Linux TID and the GDB thread ID with info threads command.

Hope this helps.

Upvotes: 3

Related Questions