-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_example.c
62 lines (45 loc) · 1.24 KB
/
thread_example.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct Student {
int age;
char *name;
};
void *threadFunction(void*);
void init(struct Student*, int, char*);
int main() {
int age;
char name[50];
// taking input from user //
/**********************************/
printf("Enter student name: ");
scanf("%[^\t\n]", name);
printf("Enter student age: ");
scanf("%d", &age);
/**********************************/
//declaring student object
struct Student student;
//initializing student object
init(&student, age, name);
pthread_t tid;
//creating thread and passing student object as thread parameter
pthread_create(&tid, NULL, threadFunction, (void*) &student);
//wating for the thread
pthread_join(tid, NULL);
printf("\n");
return 0;
}
void *threadFunction(void *params) {
int age = ((struct Student *) params)->age;
char *name = ((struct Student *) params)->name;
printf("\nName: %s", name);
printf("\nAge: %d", age);
free(name);
return NULL;
}
void init(struct Student *obj, int age, char *name) {
obj->age = age;
obj->name = malloc(strlen(name) + 1);
strcpy(obj->name, name);
}