Skip to content

Instantly share code, notes, and snippets.

@carlosvin
Last active August 31, 2019 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosvin/11257689 to your computer and use it in GitHub Desktop.
Save carlosvin/11257689 to your computer and use it in GitHub Desktop.
Mutex C++98
#include "Mutex.h"
#include <iostream>
#include <list>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;
Mutex mtx;
list<int> sharedElements;
int e = 0;
void printE(char action, unsigned element)
{
printf("%c%u\t[%u]\n", action, element, pthread_self());
}
void * addE(void * arg)
{
mtx.lock();
sharedElements.push_back(e);
printE('+',e++);
mtx.unlock();
return 0;
}
void * removeE(void * arg)
{
mtx.lock();
if (sharedElements.empty())
{
printE('#', sharedElements.front());
mtx.unlock();
usleep(100000);
removeE(0);
}
else
{
printE('-',sharedElements.front());
sharedElements.pop_front();
mtx.unlock();
}
return 0;
}
int main(void)
{
const int MAX_THS = 10;
pthread_t thAdd[MAX_THS], thRem[MAX_THS];
for (unsigned i=0; i<MAX_THS; i++)
{
pthread_create(&thAdd[i], NULL, addE, NULL);
pthread_create(&thRem[i], NULL, removeE, NULL);
}
for (int i=0; i<MAX_THS; i++)
{
pthread_join(thRem[i], NULL);
pthread_join(thAdd[i], NULL);
}
return 0;
}
#include "Mutex.h"
#include <exception>
Mutex::Mutex()
{
if ( pthread_mutex_init(&_mutex, NULL) )
{
throw "Error: Initializing _mutex";
}
}
Mutex::~Mutex()
{
pthread_mutex_destroy(&_mutex);
}
Mutex::Mutex(const Mutex & obj)
{
_mutex = obj._mutex;
}
Mutex & Mutex::operator=(const Mutex & obj)
{
_mutex = obj._mutex;
return *this;
}
bool Mutex::operator==(const Mutex & obj)
{
return _mutex == obj._mutex;
}
bool Mutex::operator!=(const Mutex & obj)
{
return !(*this == obj);
}
void Mutex::lock ()
{
pthread_mutex_lock( &_mutex );
}
void Mutex::unlock ()
{
pthread_mutex_unlock( &_mutex );
}
void Mutex::lock ( int lock, Mutex * mtx)
{
if (lock)
{
mtx->lock();
}
else
{
mtx->unlock();
}
}
#ifndef MUTEX_H_
#define MUTEX_H_
#include <pthread.h>
class Mutex
{
private:
pthread_mutex_t _mutex;
Mutex & operator=(const Mutex & obj);
Mutex(const Mutex & obj);
public:
Mutex();
virtual ~Mutex();
bool operator==(const Mutex & obj);
bool operator!=(const Mutex & obj);
void lock();
void unlock();
static void lock ( int lock, Mutex * mtx);
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment