-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_1_baselined.c
More file actions
82 lines (73 loc) · 2.15 KB
/
thread_1_baselined.c
File metadata and controls
82 lines (73 loc) · 2.15 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/***************************************************************************
* FILENAME :thread_1.c
* DESCRIPTION:Contains Code for a program that demonstrates the
* use of pthread calls.The created threads will accept an
* argument and return the argument after adding a number.
* Compile using gcc lfy_thread_1.c -o mythread -lpthread
* run in the shell prompt providing a number as cmd line arg.
****************************************************************************/
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct ThreadIdAndData
{
pthread_t thread; //Thread identifer
int value; //Value passed to Thread
int status; //keeps track if this is a valid thread
} ThreadIdAndData;
void *thread_entry(void *arg)
{
int *p;
p=(int*)arg;
*p = (*p) + 10;
pthread_exit(p);
}
int main(int argc, char* argv[])
{
ThreadIdAndData* threads;
int t;
int ret;
int numthreads = 0;
void* thread_result;
if (( argc < 2 ) || ((numthreads = atoi(argv[1])) <= 0))
{
printf("Usage: %s <number>\nThe number(should be > 0) represents the number of threads to start\n", argv[0]);
exit(1);
}
threads = calloc(numthreads, sizeof(ThreadIdAndData));
if (NULL == threads)
{
printf("Failed to alocate memory in malloc\n");
exit(1);
}
/*Creating the Threads*/
for(t=0; t < numthreads; t++)
{
printf("Creating Thread\n");
threads[t].value = t;
threads[t].status = pthread_create(&threads[t].thread,NULL,thread_entry,(void*)&threads[t].value);
//Non zero returns means the pthread_create failed
if(threads[t].status )
{
printf("Error Creating Thread\n");
}
}
//Now waiting for all the threads using pthread_join
for(t=0; t < numthreads; t++)
{
if (threads[t].status == 0)//Threads which were created successfully
{
ret = pthread_join(threads[t].thread, &thread_result);
if(ret)
{
printf("Error joining a thread");
}
else
{
printf("Joined thread returned %d\n", *((int*)thread_result));
}
}
}
free(threads);
return 0;
}