Saturday, July 2, 2011

Under the hood of pthread


Hi all,

Today I’ll be talking about the implementation of user space threads in Linux .
Nowadays almost every program on your pc holds multiple threads. Threads as we know it, share open files, resources and memory address space.

The interesting fact about Linux kernel is, it sees threads as standard processes, so it doesn’t provide any special treatment for dealing with them. From the kernel point of view a thread is just a process which shares few resources with other processes. This approach makes things much easier and elegant than Windows approach for distinguishing between a process and thread.

So now let’s see what happens when we create a thread using the pthread_create() method:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void * thread1()
{
  while(1)
  {
      printf("Hello!!\n");
  }
}

void * thread2()
{
   while(1)
   {
      printf("How are you?\n");
   }
}

int main()
{
 int status;
 pthread_t tid1,tid2;
 pthread_create(&amp;tid1,NULL,thread1,NULL);
 pthread_create(&amp;tid2,NULL,thread2,NULL);
 return 0;
}

The POSIX library methods creates threads the same as normal tasks, except it calls the system call clone().
Yes you heard right, the system call clone() has been invoked. You can check and see
for youself With the strace tool, which I wrote here a month ago. I’ll show you the output of the trace file showing that there was indeed a system call named clone().

... clone(child_stack=0xb7768494, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND| CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS| CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0xb7768bd8, {entry_number:6, base_addr:0xb7768b70, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}, child_tidptr=0xb7768bd8) = 5877 ...

We can see from the straceout file which I generated, that to the clone() system call were passed flags.
So what do you think those flags stand for?
Those flags say which resources are being shared, so they are actually responsible for the difference between a simple process to a thread in Linux. The flags help specifying in detail which resources the parent and child will share.
I’ll try to explain few of the flags in the example above, for more information you can check for yourself in  <linux/sched.h>:

Flag Name
Short explanation
CLONE_VM
Parent and child share address space
CLONE_FS
Parent and child share filesystem information
CLONE_FILES
Parent and child share open files
CLONE_SIGHAND
Parent and child share signal handlers and blocked signals
CLONE_THREAD
Parent and child are in the same thread group


Pretty neat, right? :-)
yap interesting stuff…

unfortunately I gotta go, so that’s it for today, next time I’ll be talking about Kernel threads!!

No comments:

Post a Comment

About