summaryrefslogtreecommitdiff
path: root/tests/threads/test_counter_mutex.c
blob: 4b7324c71d7151a24bfeb6f29fb5a2c66c8c920b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "threads/threads.h"
#include "threads/mutex.h"
#include "port/unused.h"

#include <stdlib.h>		/* for EXIT_SUCCESS, EXIT_FAILURE */
#include <stdio.h>		/* for fprintf */


#define USE_MUTEX 1

#define NOF_LOOPS 10
#define NOF_THREADS 10
#if USE_MUTEX
#define NOF_ITERATIONS 100000
#else
#define NOF_ITERATIONS 1000000
#endif

static int counter = 0;
#if USE_MUTEX
static wolf_mutex_t counter_mutex;
#endif

static WOLF_THREAD_RETURN_DECL thread_func( void *thread_data ) {
	int i;

	for( i = 0; i < NOF_ITERATIONS; i++ ) {
#if USE_MUTEX
		wolf_mutex_lock( &counter_mutex );
#endif
		counter++;
#if USE_MUTEX
		wolf_mutex_unlock( &counter_mutex );
#endif
	}

	WOLF_UNUSED( thread_data );

	WOLF_THREAD_RETURN
}

int main( void ) {
	int i;
	int j;
	wolf_thread_t thread[NOF_THREADS];
	wolf_error_t error;

#if USE_MUTEX
	error = wolf_mutex_init( &counter_mutex );
	if( error != WOLF_OK ) {
		fprintf( stderr, "Unable to create mutex: %d\n", error );
		return EXIT_FAILURE;
	}
#endif

	for( j = 0; j < NOF_LOOPS; j++ ) {
		for( i = 0; i < NOF_THREADS; i++ ) {
			error = wolf_thread_create( &thread[i], thread_func );
			if( error != WOLF_OK ) {
				fprintf( stderr, "Unable to start thread %d: %d\n", i, error );
				return EXIT_FAILURE;
			}
			printf( "Created thread %d\n", i );
			fflush( stdout );
		}
	
		for( i = 0; i < NOF_THREADS; i++ ) {
			error = wolf_thread_join( &thread[i] );
			if( error != WOLF_OK ) {
				fprintf( stderr, "Unable to join thread %d: %d\n", i, error );
				return EXIT_FAILURE;
			}
			printf( "Joined thread %d\n", i );
			fflush( stdout );
		}

		printf( "Value of counter: %d\n", counter );

		if( counter != ( j + 1 ) * NOF_THREADS * NOF_ITERATIONS ) {
			fprintf( stderr, "Counter miscounted, is %d, must %d be!\n",
				counter, ( j + 1 ) * NOF_THREADS * NOF_ITERATIONS );
			return EXIT_FAILURE;
		}
	}

#if USE_MUTEX
	error = wolf_mutex_destroy( &counter_mutex );
	if( error != WOLF_OK ) {
		fprintf( stderr, "Unable to destroy mutex: %d\n", error );
		return EXIT_FAILURE;
	}
#endif


	return EXIT_SUCCESS;
}