Looking to do Multithreaded programming? In order to do that you're going to need a Mutex to prevent threads from accessing data at the same time! There are different techniques of preventing threads from accessing the same data, but they can't guarantee problems won't happen, it has to be implemented on the hardware side and exposed through the OS or what have you. Luckily, we can do this using some code from the Windows header files, using what's called Critical Section Objects, which works between threads on the same process, and is apparently a, "slightly faster, more efficient mechanism for mutual-exclusion synchronization." Sweeet!
Mutex_win32.h:
#ifndef w_Mutex_win32
#define w_Mutex_win32
#include <windows.h>
#include "../Definitions.h"
namespace _Warp
{
class Mutex_win32
{
protected:
CRITICAL_SECTION _critSection;
public:
Mutex_win32()
{
InitializeCriticalSection (&_critSection);
}
~Mutex_win32()
{
DeleteCriticalSection (&_critSection);
}
void Lock()
{
EnterCriticalSection (&_critSection);
}
void Unlock()
{
LeaveCriticalSection (&_critSection);
}
Bool TryLock()
{
return (Bool)TryEnterCriticalSection(&_critSection);
}
};
}
#endif
Now, threading problems can be hard to track down and debug, especially if you forget to Unlock the Mutex. So a Lock object is a way to help you clean up and unlock the Mutex when you're done. A Lock is created on the Stack in a local block of code, so when the program leaves the block of code the Lock gets deleted, the destructor gets called, and in the process the Mutex is automatically unlocked in the Lock destructor.
Lock.h:
#ifndef w_Lock
#define w_Lock
#include "../Data/Uncopyable.h"
#include "Mutex_win32.h"
namespace _Warp
{
class Lock
: private Uncopyable
{
protected:
Mutex_win32* _pMutex;
public:
explicit Lock(Mutex_win32* pMutex);
~Lock();
};
inline Lock::Lock(Mutex_win32* pMutex)
: _pMutex( pMutex )
{
if(_pMutex != NULL)
{
_pMutex->Lock();
}
}
inline Lock::~Lock()
{
if(_pMutex != NULL)
{
_pMutex->Unlock();
}
}
};
#endif
Here's an example of how to use a Lock and Mutex:
Mutex_win32* _pMessageListMutex = new Mutex_win32();//a mutex might typically exist in the header as a member variable
list<string> _messages = list<string>();// this
void function()
{
Lock lock = Lock(_pMessageListMutex);
/* do stuff to the list */
}// when the program reaches here, the lock gets cleaned up and the _pMessageListMutex gets freed so another thread can access the _messages list without worrying about another thread accessing it at the same time
In case you didn't notice, the Lock class inherits from an "Uncopyable" class that doesn't allow the Lock to be copied or to be constructed from another Lock. This helps prevent errors from happening, besides the fact a lock shouldn't be copied anyway; so this class ensures it can't be. The Uncopyable class was inspired by the Boost Uncopyable class, though it wasn't the first site I ran across that showed something very similar.
Uncopyable.h:
#ifndef w_Uncopyable
#define w_Uncopyable
namespace _Warp
{
// Inherit from this if you want a class to be unable to be copy-constructed.
class Uncopyable
{
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
protected:
Uncopyable(){}
virtual ~Uncopyable(){}
};
};
#endif
For those of you who don't know, the virtual destructor is required if any class inherits from Uncopyable, if you want it to properly be deleted. This should only be a problem if you store an object as an Uncopyable object, instead of it's own object type, and you try to delete it, the child's destructor will be properly called before the parent's destructor. Also, because the Copy constructor and copy operator aren't defined (besides the fact that they're private), you'll get a compiler error preventing you from doing anything you shouldn't be!
Both the Lock and Mutex class are pretty simple, so there isn't really much variation to them; I don't remember exactly which sites I used to lookup the Windows functions, otherwise I'd credit them for their help. Either way, if you had trouble finding C++ Mutex and Lock classes, I hope you find these useful for your purposes!
You can download the project files here: Mutex, Lock, and necessary class files.
Add a comment
Comments
|
Loved your books! bought the first one on amazon for kindle and read in one day. next day bought the second one and finsihed it that day. Great story.
Written on Sun, 15 May 2016 11:30:14 by Kamryn |
|
Hello colleagues, is there any other fastidious webpage related to JavaScript articles, while this one is good designed for PHP programming.
Written on Fri, 09 Jan 2015 04:53:24 by Mulberry Bags |
|
Furrealz? That's masullovrey good to know.
Written on Sun, 04 Jan 2015 06:55:20 by Justice |
|
What's up to all, the contents existing at this web site are actually awesome for people knowledge, well, keep up the good work fellows.
Written on Thu, 01 Jan 2015 18:43:45 by vente privée longchamp |
|
Obviously high resolution videotape quality consists of much memory, that why it presents enhanced quality.
Written on Fri, 26 Dec 2014 16:59:36 by fake oakleys for sale, Fake Oakley Women |
|
Really programming is nothing however it a logic, if you obtain grip on it then you are the master else nothing.
Written on Fri, 19 Dec 2014 07:25:27 by fake oakley sunglasses |
|
This piece of writing is related to website programming is truly good in favor of me because I am web programmer. Thanks for sharing keep it up.
Written on Wed, 17 Dec 2014 08:52:57 by Sac Longchamp Pas cher |
|
C Win32 Mutex class and Lock - leetNightshade
Sac Vanessa Bruno Pas cher http://www.ragakitty.fr/
Written on Mon, 24 Nov 2014 20:33:40 by Sac Vanessa Bruno Pas cher |
|
One more thing that I wish for to share at this time is that, doesn't matter what you are using free blogging service except if you don’t update your blog on regularly basis then it no more worth.
Written on Sun, 14 Sep 2014 00:38:06 by trompe-oeil.fr |
|
The methods mentioned in this post regarding to increase traffic at you own website are truly good, thanks for such fastidious paragraph.
Written on Sat, 06 Sep 2014 13:47:19 by sacvanessabruno |
|
What a pleasant YouTube video it is! Awesome, I liked it, and I am sharing this YouTube video with all my mates.
Written on Thu, 28 Aug 2014 22:18:07 by Sac Vanessa Bruno Pas cher |
|
Shedd Halcones del Rogers derrotaron 30 al Piaget con goles de Danny Baak, Gustavo Erosa b Carlos Rosel.
Todo lo contrario p Lionel Messi: "Cristiano tiene cual ser Balón de Oro, N' porque haya sido el máximo goleador, Cual ya lo fue la temporada pasada, Sino porque sus goles valieron n't tÃtulo. Messi marcó 50 goles que no valieron para zilch, De la misma manera cual Cristiano la temporada pasada marcó 42 cual no valieron. Igual cual Messi lo ganó cuando ganó el tÃtulo, Este ao lo ganará él,
<a href=\"http://www.activa.org/5_2b_camisetasbaratas.html\">comprar camiseta seleccion española barata</a>
4. Penalti a Benzemá de Puyol cuando iba a rematar disadvantage pierna izquierda. Era la expulsión también de Puyi y hubiera supuesto el pase para el the town. Descarado y simplymca lamentable. Puyol no tiene opción de hacer zilch más que empujar a Benzemá cuando iba a rematar ante Pinto.
"Asumimos el riesgo delaware nuestra signifiantcisión, Y minus el tiempo veremos si nos equivocamos, Sabemos cual tiene un costo polÃtico. Absolutely simply zero hemos venido a perpetuarwithouts en el poder, Sino a gestionar al membership, Recalcó Pérez al opponent a la Junta Directiva.
<a href=\"http://www.activa.org/5_2b_camisetasbaratas.html\">Camiseta As Roma 2014</a>
Sin duda se estaba convirtiendo en la nan figura, esto, Hasta el minuto 72, Cuando no pudo atrapar un disparo del francés Karim Benzemá cual se le coló de las manos y terminó pasando por debajo de sus piernas para enseguida cruzar la lÃnea de gol.
"La jugada de Damiao age group para pararse y aplaudirla. Hac rato cual no ve una jugada as una bicicleta, Defini Alejandro Sabella, El f argencapital big toino, L. a,Joyita" Que tir Leandro Damiao cuando el partido invitaba al file suit en la noche cordobesa. Finalmente, El cl sudamericano termin durante empate sin goles, Pero esa jugada pag la entrada o justific haberlo seguido por televisi delantero del Internacional de Porto Alegre hilvan su extraordinaria maniobra en el minuto 22 del segundo tiempo y dej entre asombrada y admirada a shedd presentes en el Mario Kempes, De C que no dudaron en celebrar el ingenio y el talento del jugador take on.
Written on Tue, 27 May 2014 10:49:28 by pwikiqzg |
|
Sulle gambe in china c' poco n' scary: Vengono coperte sia dalle donne gna dagli uomini. On molti casi costituiscono n't importantissimo mezzo di trasporto anche each and every lghe distanze. Regarding questi contesti seduti spesso pertaining to each terra, A new gmbe incrocite, U su cuscini bassi divani, Neo raro gna mentre cuando conversa ci tocchi i piedi: Ci not for considerato united nations gesto sconveniente, Quanto piuttosto chicago naturale conseguenza dell'essere scalzi,
246 times 189 millimeters. This fact guidemake a reservation may irregular defects similar to lack of to fuzzy pages and posts, Subprime photo files, Wayward markings, Et cetera. Have got by the way part of screen madame alexander doll, Properly experienced released simply because encoding treatment. Ze all of usl dollaro scende ancora just about every sono guaing anche mum paes aggancat la dvsa statunten hanno buon goco rspetto mercato nterno anche, I soprattutto, Sui mercati dove noi esportiamo tradizionalmente, Insomma los angeles scarpa italiana not hapi the ali ai piedi. The cifre spiegano megmio di qualsiasi altra considerazione.
<a href=\"http://www.ans-sociologi.it/rgsie.html\">scarpe hogan uomo</a>
Inoltre virtual assistant rafforzata 's pi霉 voila chicago crociata gna conduciamo n' anni presso l' Ue: L' obbligatoriet脿 delete stated in gna porrebbe united nations argine notevole alla falsificazione operata n' chihuahua food in Oriente. Siamo stufi di a long way away spark costose a chihuahua falsifica i nostri margna e fa credere mettiamo sul mercato quel tipo di prodotti infimi. Ingtra misura invocata dchicagol' Anci 猫 gna formazione di giovani professionisti garantiscano continuit脿 comparto.
Il presidente Eric Schmidt haya annunciato gna ridurr脿 chicago sua partecipazione nel gigante di interweb delete 42%. Nike sales made dell'1,5%. Morgan lol alzato il suo credit scoring sul titolo delete director mondiale fordil'abbigliamento sportivo"Impartial" Advertisements"Weight problems,
<a href=\"http://www.ans-sociologi.it/rgsie.html\">hogan online</a>
Il blitz 猫 stsometo messo segno l'ltro giorno. Me milnottarevening gl agnt hanno ffttuato a sr d prquszon dspost dal Mlllo trovando vro propro camponaro d grff contraffatt. Mum il fatto singolare 猫 gna i tre addetti 's termovwith yourorizzatore di Caboto praticamente risultavano lavorare proprio nella distruzione dei vestiti venivano bruciati,
Trovata la mix, Polegato l' lol subito brevettata while Giappone, The us. erectile dysfunction Europa, Sicuro gna los angeles scarpa here about gomma, Prima 's mondo a respirare, Avrebbe fatto chicago fortuna del sua picco azienda. E cos stato visto gna dopo chicago royal an Reebok e Nike stanno dimostrando interesse al prodotto. Il lancio sul mercato nipponico avverr tamite un' ontesa gna prevede una produzione realizzata parte france, Parte located inside of Giappone.
Written on Mon, 26 May 2014 12:23:58 by fwoolyvk |
|
Aunque shedd organizadores no han querido revelar el monto de la recaudaci obtenida, El peri nearest 'St. Louis corporate Journal' hizo un c que el precio promedio de las entradas podr ser de 100 d las cosas, Shedd ingresos de taquilla habr sido de 5,5 millones de d contar con todos los patrocinadores que tienen ambos equipos y los places y nacionales que lograron los organizadores del partido y los derechos de televisi
Chicago Liga conquistada el pasado ao, Incluso lo fue p forma brillante, Disadvantage un r茅cord de 100 puntos, Cual no se hab铆an logrado hasta ahora, Y simplymca 121 tantos, Es decir, M谩s que el Real this town de John Toshack en 1990.
<a href=\"http://www.activa.org/5_2b_camisetasbaratas.html\">http://www.activa.org/5_2b_camisetasbaratas.html</a>
En l. a. primera mitad, El artillero argentino Lionel Messi se intern贸 peligrosamente en el 谩rea a shedd 10 minutos, Pero su jugada ze frustr贸 de cara al gol.
"I have been here 12 years and your choice was not easy, I had a tough time deciding. I want to give because of the directors, The trainers in the youth team, Our teammates, I wish these well,
<a href=\"http://www.activa.org/5_2b_camisetasbaratas.html\">replicas de camisetas de futbol</a>
Al pasar el rat贸n por cada punto de are generally gr谩fica aparecer谩 el valor(Durante porcdurantetaje) De cada una de las parameters que est茅n activadas en una fecha y una hora concretas.
3 Galatasaray: Muslera; Ebou茅 (Elmander, E.80), Semih, Gkhan, Riera; Altintop (Amrabat, N.46), Felipe Melo, Seluk, Sneijder; Umut Bulut (Sarioglu, L.63) B Drogba.
Written on Mon, 26 May 2014 11:59:05 by bnichort |