- Define a variable of the type pthread_t to store the thread identifier:
pthread_t tid;
- Create a thread and pass the identifier that was created in the preceding step to the pthread_create function. The thread is created with the default attributes. Also, specify a function that needs to be executed to create the thread:
pthread_create(&tid, NULL, runThread, NULL);
- In the function, you will be displaying a text message to indicate that the thread has been created and is running:
printf("Running Thread \n");
- Invoke a for loop to display the sequence of numbers from 1 to 5 through the running thread:
for(i=1;i<=5;i++) printf("%d\n",i);
- Invoke the pthread_join method in the main function to make the main method wait until the thread completes its task:
pthread_join(tid, NULL);
The createthread.c program for creating a thread and making it perform a task is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *runThread(void *arg)
{
int i;
printf("Running Thread \n");
for(i=1;i<=5;i++) printf("%d\n",i);
return NULL;
}
int main()
{
pthread_t tid;
printf("In main function\n");
pthread_create(&tid, NULL, runThread, NULL);
pthread_join(tid, NULL);
printf("Thread over\n");
return 0;
}
Now, let's go behind the scenes.