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 	pthread_condattr_t att = {0};
53 
54 	zassert_ok(pthread_condattr_init(&att));
55 
56 	zassert_ok(pthread_condattr_destroy(&att));
57 }
58 
59 /**
60  * @brief Test pthread_cond_init() with a pre-existing initialized attribute.
61  */
ZTEST(cond,test_cond_init_existing_initialized_condattr)62 ZTEST(cond, test_cond_init_existing_initialized_condattr)
63 {
64 	pthread_cond_t cond;
65 	pthread_condattr_t att = {0};
66 
67 	zassert_ok(pthread_condattr_init(&att));
68 	zassert_ok(pthread_cond_init(&cond, &att), "pthread_cond_init failed with valid attr");
69 
70 	/* Clean up */
71 	zassert_ok(pthread_cond_destroy(&cond));
72 	zassert_ok(pthread_condattr_destroy(&att));
73 }
74 
75 ZTEST_SUITE(cond, NULL, NULL, NULL, NULL, NULL);
76