-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.c
98 lines (83 loc) · 2.02 KB
/
async.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/**
* Parameters to be passed into the
* thread runner function
* */
typedef struct parameters
{
pthread_t thread; // threadId
int value; // some value (one of the parameters we need)
int (*callback)(void *param); // completion callback
} threadParam;
/**
* Completion Callback for the thread function
* */
int completionCallback(void *param)
{
printf("CALLBACK INITIAL STAGE\n");
// Some callback stuff
printf("CALLBACK ENDS\n");
}
/**
* Runner for the thread
* */
void *runner(void *arg)
{
printf("Process Start\n");
sleep(2);
threadParam *para = (threadParam *)arg;
printf("Calling Callback\n");
para->callback(para);
}
/**
* Synchronised Execution using Threads
* */
void syncExecutor(int value)
{
pthread_t thread;
threadParam *tp = (threadParam *)malloc(sizeof(threadParam));
tp->thread = thread;
tp->value = value;
tp->callback = &completionCallback;
int returnValue = pthread_create(&thread, NULL, runner, tp);
if (returnValue != 0)
{
printf("Error In Threads");
exit(0);
}
pthread_join(thread, NULL);
}
/**
* Asynchronised Execution using Threads
* */
void asyncExecutor(int value)
{
pthread_t thread;
pthread_attr_t attributes;
pthread_attr_init(&attributes);
pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
threadParam *tp = (threadParam *)malloc(sizeof(threadParam));
tp->thread = thread;
tp->value = value;
tp->callback = &completionCallback;
int returnValue = pthread_create(&thread, &attributes, runner, tp);
if (returnValue != 0)
{
printf("Error In Threads");
exit(0);
}
//pthread_detach(thread);
}
int main()
{
// 5 is just a value taken for example
syncExecutor(5);
syncExecutor(5);
// Uncomment the below part to run asynchronised tasks
// asyncExecutor(5);
// asyncExecutor(5);
pthread_exit(NULL);
}