forked from remzi-arpacidusseau/ostep-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ordering_fixed.c
66 lines (51 loc) · 1.43 KB
/
ordering_fixed.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "common.h"
#include "common_threads.h"
#define PR_STATE_INIT (0)
typedef struct {
pthread_t Tid;
int State;
} pr_thread_t;
pr_thread_t *PR_CreateThread(void *(*start_routine)(void *)) {
pr_thread_t *p = malloc(sizeof(pr_thread_t));
if (p == NULL)
return NULL;
p->State = PR_STATE_INIT;
Pthread_create(&p->Tid, NULL, start_routine, NULL);
// turn the sleep off to avoid the fault, sometimes...
sleep(1);
return p;
}
void PR_WaitThread(pr_thread_t *p) {
Pthread_join(p->Tid, NULL);
}
pr_thread_t *mThread;
pthread_mutex_t mtLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mtCond = PTHREAD_COND_INITIALIZER;
int mtInit = 0;
void *mMain(void *arg) {
printf("mMain: begin\n");
// wait for thread structure to be initialized
Pthread_mutex_lock(&mtLock);
while (mtInit == 0)
Pthread_cond_wait(&mtCond, &mtLock);
Pthread_mutex_unlock(&mtLock);
int mState = mThread->State;
printf("mMain: state is %d\n", mState);
return NULL;
}
int main(int argc, char *argv[]) {
printf("ordering: begin\n");
mThread = PR_CreateThread(mMain);
// signal: thread has been created, and mThread initialized
Pthread_mutex_lock(&mtLock);
mtInit = 1;
Pthread_cond_signal(&mtCond);
Pthread_mutex_unlock(&mtLock);
PR_WaitThread(mThread);
printf("ordering: end\n");
return 0;
}