jhpratt / num_threads

Obtain the number of threads in the current process
https://docs.rs/num_threads
Apache License 2.0
12 stars 7 forks source link

Use `unshare` on Linux when you don't need the full count #9

Open o11c opened 2 years ago

o11c commented 2 years ago

From the man page unshare(2):

   In addition, CLONE_THREAD, CLONE_SIGHAND, and CLONE_VM can be
   specified in flags if the caller is single threaded (i.e., it is
   not sharing its address space with another process or thread).
   In this case, these flags have no effect.  (Note also that
   specifying CLONE_THREAD automatically implies CLONE_VM, and
   specifying CLONE_VM automatically implies CLONE_SIGHAND.)  If the
   process is multithreaded, then the use of these flags results in
   an error.
Freaky commented 2 years ago

This is quite a bit faster than checking /proc (~70x in my test env), but I'm a bit concerned about the long-term stability of this approach:

           ... In particular, as at kernel 3.8, unshare() does not
   implement flags that reverse the effects of CLONE_SIGHAND,
   CLONE_THREAD, or CLONE_VM.  Such functionality may be added in
   the future, if required.

So it'll be fine up until the point at which some smartarse actually implements the functionality the unshare call is asking for...