-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread_create.c
More file actions
42 lines (32 loc) · 735 Bytes
/
thread_create.c
File metadata and controls
42 lines (32 loc) · 735 Bytes
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
#include "types.h"
#include "stat.h"
#include "user.h"
#define PAGESIZE 4096
int
thread_create(void (*fn) (void *), void *arg)
{
// allocating 2 * pageSize for fptr in heap
void *fptr = malloc(2 * (PAGESIZE));
void *stack;
if(fptr == 0)
return -1;
int mod = (uint)fptr % PAGESIZE;
// the following if-else is for assigning page-aligned space to stack
if(mod == 0)
stack = fptr;
else
stack = fptr + (PAGESIZE - mod);
int thread_id = clone((void*)stack);
// clone failed
if(thread_id < 0)
printf(1, "clone failed\n");
// child
else if(thread_id == 0){
// call the function passed to thread_create
(fn)(arg);
// free space when function is finished
free(stack);
exit();
}
return thread_id;
}