]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/libstrongswan/tests/test_threading.c
0c768b3e2ac6409557dcf696a2e5003952b0fc5d
[thirdparty/strongswan.git] / src / libstrongswan / tests / test_threading.c
1 /*
2 * Copyright (C) 2013 Tobias Brunner
3 * Copyright (C) 2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <sched.h>
18 #include <pthread.h>
19
20 #include "test_suite.h"
21
22 #include <threading/mutex.h>
23
24 /*******************************************************************************
25 * recursive mutex test
26 */
27
28 #define THREADS 20
29
30 static mutex_t *mutex;
31
32 static pthread_barrier_t mutex_barrier;
33
34 static int mutex_locked = 0;
35
36 static void *mutex_run(void *data)
37 {
38 int i;
39
40 /* wait for all threads before getting in action */
41 pthread_barrier_wait(&mutex_barrier);
42
43 for (i = 0; i < 100; i++)
44 {
45 mutex->lock(mutex);
46 mutex->lock(mutex);
47 mutex->lock(mutex);
48 mutex_locked++;
49 sched_yield();
50 if (mutex_locked > 1)
51 {
52 fail("two threads locked the mutex concurrently");
53 }
54 mutex_locked--;
55 mutex->unlock(mutex);
56 mutex->unlock(mutex);
57 mutex->unlock(mutex);
58 }
59 return NULL;
60 }
61
62 START_TEST(test_mutex)
63 {
64 pthread_t threads[THREADS];
65 int i;
66
67 mutex = mutex_create(MUTEX_TYPE_RECURSIVE);
68
69 for (i = 0; i < 10; i++)
70 {
71 mutex->lock(mutex);
72 mutex->unlock(mutex);
73 }
74 for (i = 0; i < 10; i++)
75 {
76 mutex->lock(mutex);
77 }
78 for (i = 0; i < 10; i++)
79 {
80 mutex->unlock(mutex);
81 }
82
83 pthread_barrier_init(&mutex_barrier, NULL, THREADS);
84 for (i = 0; i < THREADS; i++)
85 {
86 pthread_create(&threads[i], NULL, mutex_run, NULL);
87 }
88 for (i = 0; i < THREADS; i++)
89 {
90 pthread_join(threads[i], NULL);
91 }
92 pthread_barrier_destroy(&mutex_barrier);
93
94 mutex->destroy(mutex);
95 }
96 END_TEST
97
98 Suite *threading_suite_create()
99 {
100 Suite *s;
101 TCase *tc;
102
103 s = suite_create("threading");
104
105 tc = tcase_create("recursive mutex");
106 tcase_add_test(tc, test_mutex);
107 suite_add_tcase(s, tc);
108
109 return s;
110 }