Skip to content

Instantly share code, notes, and snippets.

@Hikari9
Last active April 10, 2016 14:24
Show Gist options
  • Select an option

  • Save Hikari9/dd2dc96f760a31018179adfe8dccd270 to your computer and use it in GitHub Desktop.

Select an option

Save Hikari9/dd2dc96f760a31018179adfe8dccd270 to your computer and use it in GitHub Desktop.
Semaphore Class and Shared Memory Class
#ifndef INCLUDE_SEMAPHORE
#define INCLUDE_SEMAPHORE 1
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <unistd.h>
class semaphore {
private:
int _id, _key;
static sembuf WAIT[2], SIGNAL[1];
public:
semaphore(): _id(-1) {}
semaphore(int key) {this->key(key);}
void key(int new_key) {
// set semaphore's key
_key = new_key;
_id = semget(_key, 1, IPC_CREAT | 0666);
}
inline int id() const {return _id;}
inline int key() const {return _key;}
inline int wait() const {return id() == -1 ? -1 : semop(id(), (sembuf*) WAIT, 2);}
inline int signal() const {return id() == -1 ? -1 : semop(id(), (sembuf*) SIGNAL, 1);}
};
sembuf semaphore::WAIT[2] = {{0, 0, SEM_UNDO}, {0, 1, SEM_UNDO | IPC_NOWAIT}};
sembuf semaphore::SIGNAL[1] = {{0, -1, SEM_UNDO | IPC_NOWAIT}};
#endif /* __INCLUDE_SEMAPHORE__ */
#ifndef INCLUDE_SHARED_MEMORY
#define INCLUDE_SHARED_MEMORY 1
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <unistd.h>
template <class type>
class memory {
private:
int id, bytes, key;
type* address;
public:
memory(int key, int bytes = sizeof(type)):
key(key),
bytes(bytes)
{
id = shmget(key, bytes, IPC_CREAT | 0666);
address = (type*) shmat(id, NULL, 0);
}
inline int getId() const {return id;}
inline int getBytes() const {return bytes;}
inline int getKey() const {return key;}
inline void write(type x) const {memcpy(data(), &x, bytes);}
inline void write(type* x) const {memcpy(data(), x, bytes);}
inline type* data() const {return address;} // pointer to data
inline type read() const {return *address;} // actual value of data
};
#endif /* INCLUDE_SHARED_MEMORY */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment