pthreads are posix threads supported by the unix based systems. The pthread library allows us to create multiple threads in the user space and execute varions operations in each of the thread. Let us see how we can create a thread using posix thread library.
The function to create a thread is
Arguments:
Thus to create a thread
Declare a variable of kind pthread_t
Declare a variable of kind pthread_attr_t
Create a function which needs to be executed in the thread.
For e.g.
We will need pass a pointer to the above funtion to pthread_create and as we are not sending any arguments to the function we can pass NULL in the arg field of pthread_crate.
Thus to create thread with default attributes and which will execute the function hello will look as follows
Once the thread is created by the parent thread should wait for the completion of the child thread Because if the parent thread gets killed, the child thread will automatically be killed and hence the operations of the child thread will never be executed.
To make the parent thread wait for the children threads we make use of the function pthread_join .
Arguments:
Thus to make the parent thread to wait for the child thread
We will need a variable
ptread_join will look as follows.
Thus the whole code to create a thread using pthread create will look as follows.
create_thread.c
To compile a program that used the pthread library we need to pass the option
-pthread to gcc to ling the required libraries and compile it successfully.
The output should be:
We can see that the parent thread creates a thread and waits for it to complete before exiting. If we removed the pthread_join(and the print of return value) from our program the output would look as below.
As the parent thread did not wait for the child thread, the child thread never got a chance to exit as it got killed as soon as the parent exited.
No comments:
Post a Comment