Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: detect at runtime that a process have multiple threads

I'm asking about linux with recent glibc.

Is there a way to detect that process consist of 1 thread or of several threads?

Threads can be created by pthread, or bare clone(), so I need something rather universal.

UPD: I want to detect threads of current process from it itself.

like image 355
osgx Avatar asked Nov 08 '10 16:11

osgx


People also ask

How can I tell if a program is multi threaded?

In taskmanager, right-click the game process and set the affinity to one core. Play a little ingame and check your fps. Then change affinity to two cores, if your fps increases then the game is (properly) multithreaded.

Can multiple threads run at the same time?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

How many threads does a process have?

Every process has at least one thread, but there is no maximum number of threads a process can use. For specialized tasks, the more threads you have, the better your computer's performance will be. With multiple threads, a single process can handle a variety of tasks simultaneously.


1 Answers

Check if directory /proc/YOUR_PID/task/ contains only one subdirectory. If you have more than one thread in process there will be several subdirs.

The hardlink count can be used to count the subdirectories. This function returns the current number of threads:

#include <sys/stat.h>

int n_threads(void)
{
    struct stat task_stat;

    if (stat("/proc/self/task", &task_stat))
        return -1;

    return task_stat.st_nlink - 2;
}
like image 117
Victor Sorokin Avatar answered Oct 13 '22 08:10

Victor Sorokin