1 /* main.c - Hello World demo */
2
3 /*
4 * Copyright (c) 2012-2014 Wind River Systems, Inc.
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 #include <zephyr/kernel.h>
10 #include <zephyr/sys/printk.h>
11
12 /*
13 * The hello world demo has two threads that utilize semaphores and sleeping
14 * to take turns printing a greeting message at a controlled rate. The demo
15 * shows both the static and dynamic approaches for spawning a thread; a real
16 * world application would likely use the static approach for both threads.
17 */
18
19
20 /* size of stack area used by each thread */
21 #define STACKSIZE 1024
22
23 /* scheduling priority used by each thread */
24 #define PRIORITY 7
25
26 /* delay between greetings (in ms) */
27 #define SLEEPTIME 500
28
29
30 /*
31 * @param my_name thread identification string
32 * @param my_sem thread's own semaphore
33 * @param other_sem other thread's semaphore
34 */
helloLoop(const char * my_name,struct k_sem * my_sem,struct k_sem * other_sem)35 void helloLoop(const char *my_name,
36 struct k_sem *my_sem, struct k_sem *other_sem)
37 {
38 while (1) {
39 /* take my semaphore */
40 k_sem_take(my_sem, K_FOREVER);
41
42 /* say "hello" */
43 printk("%s: Hello World from %s!\n", my_name, CONFIG_ARCH);
44
45 /* wait a while, then let other thread have a turn */
46 k_msleep(SLEEPTIME);
47 k_sem_give(other_sem);
48 }
49 }
50
51 /* define semaphores */
52
53 K_SEM_DEFINE(threadA_sem, 1, 1); /* starts off "available" */
54 K_SEM_DEFINE(threadB_sem, 0, 1); /* starts off "not available" */
55
56
57 /* threadB is a dynamic thread that is spawned by threadA */
58
threadB(void * dummy1,void * dummy2,void * dummy3)59 void threadB(void *dummy1, void *dummy2, void *dummy3)
60 {
61 ARG_UNUSED(dummy1);
62 ARG_UNUSED(dummy2);
63 ARG_UNUSED(dummy3);
64
65 /* invoke routine to ping-pong hello messages with threadA */
66 helloLoop(__func__, &threadB_sem, &threadA_sem);
67 }
68
69 K_THREAD_STACK_DEFINE(threadB_stack_area, STACKSIZE);
70 static struct k_thread threadB_data;
71
72 /* threadA is a static thread that is spawned automatically */
73
threadA(void * dummy1,void * dummy2,void * dummy3)74 void threadA(void *dummy1, void *dummy2, void *dummy3)
75 {
76 ARG_UNUSED(dummy1);
77 ARG_UNUSED(dummy2);
78 ARG_UNUSED(dummy3);
79
80 /* spawn threadB */
81 k_thread_create(&threadB_data, threadB_stack_area, STACKSIZE,
82 threadB, NULL, NULL, NULL,
83 PRIORITY, 0, K_NO_WAIT);
84
85 /* invoke routine to ping-pong hello messages with threadB */
86 helloLoop(__func__, &threadA_sem, &threadB_sem);
87 }
88
89 K_THREAD_DEFINE(threadA_id, STACKSIZE, threadA, NULL, NULL, NULL,
90 PRIORITY, 0, 0);
91