Brijesh Valera
Brijesh Valera

Reputation: 1117

What flags should i have to set in clone(2) so that it will work same as pthread_create()?

I have done a strace(1) of pthread_create(3). It indirectly calls the clone(2) system call.

And there it will set following flags: (I'm using i386 GNU/Linux (Mint 13))

CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID

I am good with this all flags. But my question is why does pthread_create() set CLONE_CHILD_CLEARTID flag? According to my knowledge CLONE_CHILD_SETTID will set child thread id at location ctid in child memory and CLONE_CHILD_CLEARTID will erase it while child exits.

(Because there is no CLONE_CHILD_SETTID flag set, then why CLONE_CHILD_CLEARTID?)

Is it really needed? And what are ideal flags should we have to set when we want to achieve functionality of pthread_create() using clone(2)?

Beginner in this field.

Upvotes: 1

Views: 944

Answers (1)

nneonneo
nneonneo

Reputation: 179392

Well, you cannot duplicate pthread_create using only clone. clone is written to support library usage, e.g. by pthreads, but on its own it is basically a very customizable thread fork function.

CLONE_CHILD_CLEARTID, for instance, is designed to support pthread_join. What it essentially does is zero the value at ctid, then wake up threads that have called a futex_wait on that address. Thus, pthread_join can be implemented by simply checking to see if ctid is zero (and returning immediately with the status if it is), then doing a futex_wait if necessary (assuming proper synchronization).

Basically, clone is an integral part of pthread_create but it is not the only part. To support more advanced usage, like essentially everything that pthreads gives you, you will have to write library code on top of clone and other calls.

Upvotes: 5

Related Questions