1 /*
2  * Copyright (c) 2022 Meta
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <pthread.h>
8 
9 #include <zephyr/ztest.h>
10 
11 /**
12  * @brief Test to demonstrate limited condition variable resources
13  *
14  * @details Exactly CONFIG_MAX_PTHREAD_COND_COUNT can be in use at once.
15  */
ZTEST(cond,test_cond_resource_exhausted)16 ZTEST(cond, test_cond_resource_exhausted)
17 {
18 	size_t i;
19 	pthread_cond_t m[CONFIG_MAX_PTHREAD_COND_COUNT + 1];
20 
21 	for (i = 0; i < CONFIG_MAX_PTHREAD_COND_COUNT; ++i) {
22 		zassert_ok(pthread_cond_init(&m[i], NULL), "failed to init cond %zu", i);
23 	}
24 
25 	/* try to initialize one more than CONFIG_MAX_PTHREAD_COND_COUNT */
26 	zassert_equal(i, CONFIG_MAX_PTHREAD_COND_COUNT);
27 	zassert_not_equal(0, pthread_cond_init(&m[i], NULL), "should not have initialized cond %zu",
28 			  i);
29 
30 	for (; i > 0; --i) {
31 		zassert_ok(pthread_cond_destroy(&m[i - 1]), "failed to destroy cond %zu", i - 1);
32 	}
33 }
34 
35 /**
36  * @brief Test to that there are no condition variable resource leaks
37  *
38  * @details Demonstrate that condition variables may be used over and over again.
39  */
ZTEST(cond,test_cond_resource_leak)40 ZTEST(cond, test_cond_resource_leak)
41 {
42 	pthread_cond_t cond;
43 
44 	for (size_t i = 0; i < 2 * CONFIG_MAX_PTHREAD_COND_COUNT; ++i) {
45 		zassert_ok(pthread_cond_init(&cond, NULL), "failed to init cond %zu", i);
46 		zassert_ok(pthread_cond_destroy(&cond), "failed to destroy cond %zu", i);
47 	}
48 }
49 
ZTEST(cond,test_pthread_condattr)50 ZTEST(cond, test_pthread_condattr)
51 {
52 	clockid_t clock_id;
53 	pthread_condattr_t att = {0};
54 
55 	zassert_ok(pthread_condattr_init(&att));
56 
57 	zassert_ok(pthread_condattr_getclock(&att, &clock_id), "pthread_condattr_getclock failed");
58 	zassert_equal(clock_id, CLOCK_MONOTONIC, "clock attribute not set correctly");
59 
60 	zassert_ok(pthread_condattr_setclock(&att, CLOCK_REALTIME),
61 		   "pthread_condattr_setclock failed");
62 
63 	zassert_ok(pthread_condattr_getclock(&att, &clock_id), "pthread_condattr_setclock failed");
64 	zassert_equal(clock_id, CLOCK_REALTIME, "clock attribute not set correctly");
65 
66 	zassert_equal(pthread_condattr_setclock(&att, 42), -EINVAL,
67 		      "pthread_condattr_setclock did not return EINVAL");
68 
69 	zassert_ok(pthread_condattr_destroy(&att));
70 }
71 
72 ZTEST_SUITE(cond, NULL, NULL, NULL, NULL, NULL);
73