1 /*
2 * Copyright (c) 2020 Intel Corporation
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr.h>
8 #include <arch/cpu.h>
9 #include <sys/arch_interface.h>
10
11 #define NUM_THREADS 20
12 #define STACK_SIZE (1024 + CONFIG_TEST_EXTRA_STACKSIZE)
13
14 K_THREAD_STACK_EXTERN(tstack);
15 K_THREAD_STACK_ARRAY_DEFINE(tstacks, NUM_THREADS, STACK_SIZE);
16
17 static struct k_thread t[NUM_THREADS];
18
19 K_MUTEX_DEFINE(mutex);
20 K_CONDVAR_DEFINE(condvar);
21
22 static int done;
23
worker_thread(void * p1,void * p2,void * p3)24 void worker_thread(void *p1, void *p2, void *p3)
25 {
26 const int myid = (long)p1;
27 const int workloops = 5;
28
29 for (int i = 0; i < workloops; i++) {
30 printk("[thread %d] working (%d/%d)\n", myid, i, workloops);
31 k_sleep(K_MSEC(500));
32 }
33
34 /*
35 * we're going to manipulate done and use the cond, so we need the mutex
36 */
37 k_mutex_lock(&mutex, K_FOREVER);
38
39 /*
40 * increase the count of threads that have finished their work.
41 */
42 done++;
43 printk("[thread %d] done is now %d. Signalling cond.\n", myid, done);
44
45 k_condvar_signal(&condvar);
46 k_mutex_unlock(&mutex);
47 }
48
main(void)49 void main(void)
50 {
51 k_tid_t tid[NUM_THREADS];
52
53 done = 0;
54
55 for (int i = 0; i < NUM_THREADS; i++) {
56 tid[i] =
57 k_thread_create(&t[i], tstacks[i], STACK_SIZE,
58 worker_thread, INT_TO_POINTER(i), NULL,
59 NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT);
60 }
61 k_sleep(K_MSEC(1000));
62
63 k_mutex_lock(&mutex, K_FOREVER);
64
65 /*
66 * are the other threads still busy?
67 */
68 while (done < NUM_THREADS) {
69 printk("[thread %s] done is %d which is < %d so waiting on cond\n",
70 __func__, done, (int)NUM_THREADS);
71
72 /* block this thread until another thread signals cond. While
73 * blocked, the mutex is released, then re-acquired before this
74 * thread is woken up and the call returns.
75 */
76 k_condvar_wait(&condvar, &mutex, K_FOREVER);
77
78 printk("[thread %s] wake - cond was signalled.\n", __func__);
79
80 /* we go around the loop with the lock held */
81 }
82
83 printk("[thread %s] done == %d so everyone is done\n",
84 __func__, (int)NUM_THREADS);
85
86 k_mutex_unlock(&mutex);
87 }
88