1

What will happen if the pthreadId is zero in pthread_join(pthreadId, NULL) on Android ? Like the following code snippet:

pthread_join(0, NNULL);
Jerikc XIONG
  • 3,517
  • 5
  • 42
  • 71
  • 1
    Well, what happened when you tried it? Also, what would 0 signify here according to you? Any thread..? – Michael Oct 10 '18 at 08:04
  • @Michael Maybe the question is ambiguous. In fact, I need to know if there is potential risk. I will edit the question to more clearly. – Jerikc XIONG Oct 10 '18 at 08:46
  • It depends on what you think joining thread zero is supposed to mean. The `pthread_join` documentation states that _"There is no pthreads analog of ... "join with any terminated thread". If you believe you need this functionality, you probably need to rethink your application design"_. Another thing stated in the documentation is that attempting to join a previously joined thread results in undefined behavior. – Michael Oct 10 '18 at 08:51
  • @Michael Thanks for your explanation. Is "pthread is 0" valid on Android? – Jerikc XIONG Oct 10 '18 at 09:22

1 Answers1

1

pthread_join() is used to wait for termination of the thread specified by thread id. This is needed so that process should not exit before thread finishes its execution.

The thread is identified by thread id. Now if you give 0 as thread id, it will not find the thread and return an error immediately.

So, if you are using 0 as thread id for all the threads created, it's possible that before the threads finish the assigned work, the process may exit.

In my system, if I give 0 as thread id, it returned error number 3(ESRCH No thread with the ID thread could be found.)

Few points:

  • You can print the thread id and check what values are normally given for thread id to understand it better.
  • You might need the abstract type of the thread id to print its value. Please search in /usr/include/.../pthreadtypes.h to get abstract type of pthread_t. In my system its unsigned long int.

    /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:typedef unsigned long int         pthread_t;
    
  • While debugging with GDB, it assigns thread number to each thread. Next to Thread is thread id assigned by pthread_create. For thread number 1, thread id is 0x7f5750718740.

    (gdb) info threads
      Id   Target Id         Frame 
    * 1    Thread 0x7f5750718740 (LWP 9215) "a.out" 0x00007f57502f2d2d in         __GI___pthread_timedjoin_ex (
        threadid=140012979980032, thread_return=0x0, abstime=0x0, block=<optimized         out>) at pthread_join_common.c:89
      2    Thread 0x7f574fef8700 (LWP 9216) "a.out" __lll_lock_wait ()
        at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135
    

Please check Tech Easy for more information on threads.

Preeti
  • 171
  • 4