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.
Source code of Multi-Threaded Program
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
45
46
47
48
49
50
51
52
53
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define NO_OF_THREADS 3
void *my_thread_function(void *arg);
char msg[] = "My Multi-Thread Program";
int main(void)
{
int i, length;
char *str;
pthread_t mythreads[NO_OF_THREADS];
void *thread_result;
for(i = 0; i < NO_OF_THREADS; i++)
{
length = snprintf( NULL, 0, "%d", i);
str = malloc( length + 1 );
snprintf( str, length + 1, "%d", i);
if (pthread_create(&mythreads[i], NULL, my_thread_function, (void *)str))
{
printf("\nError in creating a thread!");
exit(EXIT_FAILURE);
}
}
printf("\nWaiting for the thraed to finish....");
for(i = 0; i < NO_OF_THREADS; i++)
{
if (pthread_join(mythreads[i], &thread_result))
{
printf("Error in joining this thread!");
exit(EXIT_FAILURE);
}
printf("\nThread joined successfully and it returned %s\n", (char *)thread_result);
}
exit(EXIT_SUCCESS);
printf("\nAll the threads completed!");
}
void *my_thread_function(void *arg) {
int i;
printf("my_thread_function has been started. Argument is %s\n", (int *)arg);
for (i = 0; i < 5; i++)
Compile it as
$ gcc mythreadtest.c -o mythreadtest -lpthread
Run it as
$ ./mythreadtest
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.