-
Notifications
You must be signed in to change notification settings - Fork 0
/
test1.cpp
79 lines (66 loc) · 1.79 KB
/
test1.cpp
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
extern "C" {
#include "uthread.h"
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
unsigned long g_cnt = 0;
int points_per_thread;
int quantum_usecs = 1000;
void* worker(void* arg) {
int my_tid = uthread_self();
printf("Inside tid %d\n", my_tid);
unsigned long local_cnt = 0;
unsigned int rand_state = rand();
for (int i = 0; i < points_per_thread; i++) {
double x = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
double y = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
if (x * x + y * y < 1)
local_cnt++;
}
g_cnt += local_cnt;
uthread_terminate(my_tid);
return NULL;
}
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage: ./pi <total points> <threads> [quantum_usecs]\n");
exit(1);
} else if (argc == 4) {
quantum_usecs = atoi(argv[3]);
}
int i, ret;
unsigned long totalpoints = atol(argv[1]);
int thread_count = atoi(argv[2]);
int *threads = new int[thread_count];
points_per_thread = totalpoints / thread_count;
ret = uthread_init(quantum_usecs);
if (ret != 0) {
fprintf(stderr, "uthread_init FAIL!\n");
exit(1);
}
srand(time(NULL));
for (i = 0; i < thread_count; i++) {
int tid = uthread_create(worker, NULL);
printf("tid=%d\n", tid);
threads[i] = tid;
}
for (i = 0; i < thread_count; i++) {
uthread_join(threads[i], NULL);
}
delete[] threads;
printf("Pi: %f\n", (4. * (double)g_cnt) / ((double)points_per_thread * thread_count));
return 0;
}
/*
typedef enum Priority { RED, ORANGE, GREEN } Priority;
int uthread_init(int quantum_usecs);
int uthread_create(void *(*start_routine)(void), void *arg);
int uthread_terminate(int tid);
int uthread_suspend(int tid);
int uthread_resume(int tid);
int uthread_get_tid();
int uthread_get_total_quantums();
int uthread_get_quantums(int tid);
*/