1 /* 2 DSFML - The Simple and Fast Multimedia Library for D 3 4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com) 5 6 This software is provided 'as-is', without any express or implied warranty. 7 In no event will the authors be held liable for any damages arising from the use of this software. 8 9 Permission is granted to anyone to use this software for any purpose, including commercial applications, 10 and to alter it and redistribute it freely, subject to the following restrictions: 11 12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 14 15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 16 17 3. This notice may not be removed or altered from any source distribution 18 */ 19 20 ///A module containing the Lock struct for locking DSFML mutexes. 21 module dsfml.system.lock; 22 23 import dsfml.system.mutex; 24 25 /** 26 *Automatic wrapper for locking and unlocking mutexes. 27 * 28 *Lock is a RAII wrapper for DSFML's Mutex. 29 * 30 *By unlocking it in its destructor, it ensures that the mutex will always be released when the current scope (most likely a function) ends. 31 *This is even more important when an exception or an early return statement can interrupt the execution flow of the function. 32 * 33 *For maximum robustness, Lock should always be used to lock/unlock a mutex. 34 */ 35 struct Lock 36 { 37 private Mutex m_mutex; 38 39 ///Construct the lock with a target mutex. 40 /// 41 ///The mutex passed to sf::Lock is automatically locked. 42 /// 43 ///Params: 44 /// mutex = Mutex to lock. 45 this(Mutex mutex) 46 { 47 m_mutex = mutex; 48 49 m_mutex.lock(); 50 } 51 52 ///Destructor 53 ~this() 54 { 55 m_mutex.unlock(); 56 } 57 } 58 59 unittest 60 { 61 version(DSFML_Unittest_System) 62 { 63 import dsfml.system.thread; 64 import dsfml.system.mutex; 65 import dsfml.system.sleep; 66 import core.time; 67 import std.stdio; 68 69 Mutex mutex = new Mutex(); 70 71 void mainThreadHello() 72 { 73 auto lock = Lock(mutex); 74 for(int i = 0; i < 10; ++i) 75 { 76 writeln("Hello from the main thread!"); 77 } 78 //unlock auto happens here 79 } 80 void secondThreadHello() 81 { 82 auto lock = Lock(mutex); 83 for(int i = 0; i < 10; ++i) 84 { 85 writeln("Hello from the second thread!"); 86 } 87 //unlock auto happens here 88 } 89 90 91 writeln("Unit test for Lock struct"); 92 writeln(); 93 94 writeln("Using a lock in the main and second thread."); 95 96 auto secondThread = new Thread(&secondThreadHello); 97 98 secondThread.launch(); 99 100 mainThreadHello(); 101 102 103 sleep(seconds(1));//let's this unit test finish before moving on to the next one. 104 writeln(); 105 } 106 }