-
Notifications
You must be signed in to change notification settings - Fork 2
/
10_cthreads_1.c
66 lines (59 loc) · 1.16 KB
/
10_cthreads_1.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
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <stdbool.h>
#include "clone.h"
typedef int (*cthread_f)(void *);
struct cthread {
int returned_code;
cthread_f func;
void *arg;
void *stack;
bool is_finished;
};
int
cthread_runner(void *arg)
{
struct cthread *thread = (struct cthread *) arg;
thread->returned_code = thread->func(thread->arg);
thread->is_finished = true;
return 0;
}
void
cthread_create(struct cthread *result, cthread_f func,
void *arg)
{
result->returned_code = 0;
result->func = func;
result->arg = arg;
result->is_finished = false;
thread_create_clone(cthread_runner, (void *) result,
&result->stack);
}
int
cthread_join(volatile struct cthread *thread)
{
while (! thread->is_finished)
sched_yield();
free(thread->stack);
return thread->returned_code;
}
int
func(void *arg)
{
printf("arg = %d\n", *((int *) arg));
return 200;
}
int
main()
{
struct cthread thread;
int arg = 100;
cthread_create(&thread, func, (void *) &arg);
int retcode = cthread_join(&thread);
printf("thread is joined with retcode = %d\n", retcode);
return 0;
}