-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_create.c
74 lines (51 loc) · 1.39 KB
/
thread_create.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
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define _GNU_SOURCE 1
#include "store.h"
#include "real.h"
#include <stdio.h>
struct startupinfo
{
void *(*start_routine)(void *);
void *arg;
pthread_cond_t cond;
pthread_mutex_t mutex;
};
static void cleanup(void *thread)
{
struct thread *t = (struct thread *)thread;
fprintf(stderr, "[%u] finished (normal exit)\n", t->num);
}
static void *startup(void *startupinfo)
{
struct startupinfo *sui = (struct startupinfo *)startupinfo;
void *(*start_routine)(void *) = sui->start_routine;
void *arg = sui->arg;
real_mutex_lock(&sui->mutex);
real_cond_signal(&sui->cond);
real_mutex_unlock(&sui->mutex);
struct thread *t = find_thread(pthread_self());
fprintf(stderr, "[%u] started\n", t->num);
void *res;
pthread_cleanup_push(&cleanup, t);
res = start_routine(arg);
pthread_cleanup_pop(1);
return res;
}
int pthread_create(
pthread_t *thread,
pthread_attr_t const *attr,
void *(*start_routine)(void*),
void *arg)
{
init();
struct startupinfo sui = { start_routine, arg, {}, {} };
real_cond_init(&sui.cond, 0);
real_mutex_init(&sui.mutex, 0);
real_mutex_lock(&sui.mutex);
int res = real_create(thread, attr, &startup, &sui);
real_cond_wait(&sui.cond, &sui.mutex);
real_mutex_unlock(&sui.mutex);
return res;
}