9

How to iterate through all tids of all threads of the current process? Is there some way that doesn't involve diving into /proc?

lvella
  • 12,754
  • 11
  • 54
  • 106
  • What are you trying to do? – Ed Heal Apr 07 '15 at 21:08
  • 1
    Trying to `sched_setaffinity` on threads created from libraries, outside of my code. – lvella Apr 07 '15 at 21:11
  • There is no such functionality in POSIX threads API. – Eugene Sh. Apr 07 '15 at 21:16
  • Do you have access to a `pthread_t` handle? Can you hook into those threads post-creation and call `pthread_self` from them? – Brian McFarland Apr 07 '15 at 21:16
  • 1
    Also... one possible approach would be to set the affinity of the thread that *creates* those threads since CPU affinity mask is inherited. – Brian McFarland Apr 07 '15 at 21:18
  • No. Some threads may not even be from Pthreads (can be OpenMP). That is why I am looking for a platform specific way. – lvella Apr 07 '15 at 21:19
  • Looks like '/proc' is your best bet then. And actually, I was headed down the wrong path with questions about pthread_self() anyway. You would actually need the result of `gettid()`. – Brian McFarland Apr 07 '15 at 21:20
  • I thought of setting the affinity on the creating threads, but each of my processes have its affinity defined according to their MPI rank, so I need to initialize MPI before setting the affinity. – lvella Apr 07 '15 at 21:22
  • I included a `get_tids()` implementation using `/proc/PID/task/` [in this answer](http://stackoverflow.com/a/18603766/1475978). To speed it up a bit, you can replace the `scanf()` and `snprintf()` with custom helpers. (Oops, should have used `long int` instead of `int` for parsing PIDs and TIDs, just in case they'll grow to 64-bit at some point.) – Nominal Animal Apr 08 '15 at 08:42
  • Possible duplicate of [POSIX API call to list all the pthreads running in a process](https://stackoverflow.com/questions/3475750/posix-api-call-to-list-all-the-pthreads-running-in-a-process) – Raedwald Jun 05 '18 at 16:10
  • Not duplicated because I am not interest in POSIX threads only, but any kernel thread, including OpenMP threads. – lvella Jun 05 '18 at 16:15

1 Answers1

14

The code I am using, based on reading /proc

#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>

Then, from inside a funcion:

    DIR *proc_dir;
    {
        char dirname[100];
        snprintf(dirname, sizeof dirname, "/proc/%d/task", getpid());
        proc_dir = opendir(dirname);
    }

    if (proc_dir)
    {
        /* /proc available, iterate through tasks... */
        struct dirent *entry;
        while ((entry = readdir(proc_dir)) != NULL)
        {
            if(entry->d_name[0] == '.')
                continue;

            int tid = atoi(entry->d_name);

            /* ... (do stuff with tid) ... */
        }

        closedir(proc_dir);
    }
    else
    {
        /* /proc not available, act accordingly */
    }
lvella
  • 12,754
  • 11
  • 54
  • 106