How to create a Thread using C Programming - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

How to create a Thread using C Programming

Share This

We know that Linux or Unix systems are multi-user and multi-tasking environments. Hence the processes in these environments can cooperate with each other. In a multi-threaded system, generally, threads share a segment of memory instead of allocating memory for each thread separately.

Advantages of Threads

  • It is useful to design a program to do multiple tasks simultaneously.
  • It improves the performance of the application by utilizing multiple processor cores.
  • In the case of context switching, thread switching requires the lesser effort from the operating system compared to process switching.

Drawbacks of Threads

  • The designer of a thread should be very careful otherwise it may create a huge problem due to memory sharing.
  • Debugging is very hard.
  • On a single processor system, the use of threads does not give any benefit.

In the following program, we have shown how to create a thread. First, we have defined a function, my_thread_function, which we want to run a thread.

The function pthread_create creates a thread taking my_thread_function as an argument.

Program to handle thread (mythreadtest.c)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void *my_thread_function(void *arg);
char msg[] = "My First Thread Program";
int main(void)
{
pthread_t mythread;
void *thread_result;
if (pthread_create(&mythread, NULL, my_thread_function, (void *)msg))
{
printf("Error in creating a thread!");
exit(EXIT_FAILURE);
}
printf("Waiting for the thraed to finish....");
if (pthread_join(mythread, &thread_result))
{
printf("Error in joining this thread!");
exit(EXIT_FAILURE);
}
printf("Thread joined successfully and it returned %s\n", (char *)thread_result);
printf("Message is %s\n", msg);
exit(EXIT_SUCCESS);
}
void *my_thread_function(void *arg) {
int i;
printf("my_thread_function has been started. Argument is %s\n", (char *)arg);
for (i = 0; i < 5; i++)
{
printf("I am in a thread!\n");
sleep(1);
strcpy(msg, "Bye!");
}
pthread_exit("my_thread_function is being completed.");
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Compile it as

$ gcc mythreadtest.c -o mythreadtest -lpthread

Run it as

$ ./mythreadtest
run-thread

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.