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