Does the function "pthread_create
" start the thread (starts executing its function), or does it just creates it and make it wait for the right moment to start?
pthread_create
creates the thread (by using clone
syscall internally), and return the tid (thread id, like pid). So, at the time when pthread_create
returns, the new thread is at least created. But there are no guaranties when it will be started.
From the Man: http://man7.org/linux/man-pages/man3/pthread_create.3.html
Unless real-time scheduling policies are being employed, after a call to pthread_create(), it is indeterminate which thread—the caller or the new thread—will next execute.
POSIX has the similar comment in the informative description of pthread_create
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html
There is no requirement on the implementation that the ID of the created thread be available before the newly created thread starts executing.
There is also long "Rationale" why pthread_create is single step process without separate thread creation and start_execution (as it was in good old Java epoch):
A suggested alternative to pthread_create() would be to define two separate operations: create and start. Some applications would find such behavior more natural. Ada, in particular, separates the "creation" of a task from its "activation".
Splitting the operation was rejected by the standard developers for many reasons:
The number of calls required to start a thread would increase from one to two and thus place an additional burden on applications that do not require the additional synchronization. The second call, however, could be avoided by the additional complication of a start-up state attribute.
An extra state would be introduced: "created but not started". This would require the standard to specify the behavior of the thread operations when the target has not yet started executing.
For those applications that require such behavior, it is possible to simulate the two separate steps with the facilities that are currently provided. The start_routine() can synchronize by waiting on a condition variable that is signaled by the start operation.
You may use RT scheduling; or just add some synchronization in the created thread to get exact information about it's execution. It can be also useful in some cases to manually bind the thread to specific CPU core using pthread_setaffinity_np