File: ThreadSafePrinter.h

package info (click to toggle)
primrose 6%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 5,304 kB
  • sloc: cpp: 27,318; php: 765; ansic: 636; objc: 272; sh: 136; makefile: 92; perl: 67
file content (71 lines) | stat: -rw-r--r-- 1,431 bytes parent folder | download | duplicates (30)
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
/*
 * Modification History
 *
 * 2000-October-14		Jason Rohrer
 * Created.
 *
 * 2001-January-27		Jason Rohrer
 * Converted to use MutexLock and added to minorGems source tree.
 * Changed tprintf to be static (the mutexes don't work otherwise).
 * Now we're closing the argument list.
 * Fixed so that it works with any number of arguments.
 * Changed name of print function to printf.
 *
 * 2004-March-31   Jason Rohrer
 * Fixed static memory leak.
 */

#include "minorGems/common.h"



#ifndef THREAD_SAFE_PRINTER_INCLUDED
#define THREAD_SAFE_PRINTER_INCLUDED

#include "MutexLock.h"
#include <stdio.h>

// for variable argument lists
#include <stdarg.h>

/**
 * Thread safe printf function.  Note that printf is actually thread safe 
 * anyway, so this is just to demonstrate and test locks.  It seems as
 * though printf _isn't_ thread safe on certain platforms, so this class
 * may be useful.
 *
 * @author Jason Rohrer
 */
class ThreadSafePrinter {

	public:
		
		static int printf( const char* inFormatString, ... );

	private:
		static MutexLock sLock;

	};

// initialize static members
MutexLock ThreadSafePrinter::sLock;	

inline int ThreadSafePrinter::printf( const char*inFormatString, ... ) {
		
	va_list argList;
	va_start( argList, inFormatString );
	
	sLock.lock();
	
	int returnVal = vprintf( inFormatString, argList );
	fflush( stdout );
	
	sLock.unlock();
	
	va_end( argList );

	return returnVal;
	}


#endif