1 /*
2 * Copyright (c) 2012 Travis Geiselbrecht
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23 #include <stdio.h>
24 #include <rand.h>
25 #include <err.h>
26 #include <app/tests.h>
27 #include <kernel/thread.h>
28 #include <kernel/mutex.h>
29 #include <kernel/semaphore.h>
30 #include <kernel/event.h>
31 #include <platform.h>
32
fibo_thread(void * argv)33 static int fibo_thread(void *argv)
34 {
35 long fibo = (intptr_t)argv;
36
37 thread_t *t[2];
38
39 if (fibo == 0)
40 return 0;
41 if (fibo == 1)
42 return 1;
43
44 char name[32];
45 snprintf(name, sizeof(name), "fibo %lu", fibo - 1);
46 t[0] = thread_create(name, &fibo_thread, (void *)(fibo - 1), DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
47 if (!t[0]) {
48 printf("error creating thread for fibo %d\n", fibo-1);
49 return 0;
50 }
51 snprintf(name, sizeof(name), "fibo %lu", fibo - 2);
52 t[1] = thread_create(name, &fibo_thread, (void *)(fibo - 2), DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
53 if (!t[1]) {
54 printf("error creating thread for fibo %d\n", fibo-2);
55 thread_resume(t[0]);
56 thread_join(t[0], NULL, INFINITE_TIME);
57 return 0;
58 }
59
60 thread_resume(t[0]);
61 thread_resume(t[1]);
62
63 int retcode0, retcode1;
64
65 thread_join(t[0], &retcode0, INFINITE_TIME);
66 thread_join(t[1], &retcode1, INFINITE_TIME);
67
68 return retcode0 + retcode1;
69 }
70
fibo(int argc,const cmd_args * argv)71 int fibo(int argc, const cmd_args *argv)
72 {
73
74 if (argc < 2) {
75 printf("not enough args\n");
76 return -1;
77 }
78
79 lk_time_t tim = current_time();
80
81 thread_t *t = thread_create("fibo", &fibo_thread, (void *)(uintptr_t)argv[1].u, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
82 thread_resume(t);
83
84 int retcode;
85 thread_join(t, &retcode, INFINITE_TIME);
86
87 tim = current_time() - tim;
88
89 printf("fibo %d\n", retcode);
90 printf("took %u msecs to calculate\n", tim);
91
92 return NO_ERROR;
93 }
94