Belle II Software  release-08-01-10
SemaphoreLocker Class Reference

Handles creation, locking and unlocking of System V semaphores. More...

#include <SemaphoreLocker.h>

Public Member Functions

 SemaphoreLocker (int semId)
 Lock the given semaphore.
 
 ~SemaphoreLocker ()
 Unlock.
 
void lock ()
 Lock the semaphore. More...
 
void unlock ()
 Unlock the semaphore.
 

Static Public Member Functions

static int create (key_t semkey)
 Create a new semaphore and initialize it. More...
 
static void destroy (int semId)
 Destroy the given semaphore.
 
static bool isLocked (int semId)
 Return true if the given semaphore is locked. More...
 

Private Attributes

int m_id
 semaphore id, see semget(2).
 

Detailed Description

Handles creation, locking and unlocking of System V semaphores.

create() is used to create a new semaphore with a given semaphore key.

The returned semaphore id can then be used to protect critical sections by constructing an instance of this class. The semaphore is unlocked again on destruction.

Definition at line 24 of file SemaphoreLocker.h.

Member Function Documentation

◆ create()

int create ( key_t  semkey)
static

Create a new semaphore and initialize it.

Returns the semaphore id or value < 0 on error.

Definition at line 19 of file SemaphoreLocker.cc.

20 {
21  int semid = semget(semkey, 1, IPC_CREAT | IPC_EXCL | 0600);
22  if (semid >= 0) {
23  // POSIX doesn't guarantee any particular state of our fresh semaphore
24  int semval = 1; //unlocked state
25  if (semctl(semid, 0, SETVAL, semval) == -1) { //set 0th semaphore to semval
26  B2ERROR("Initializing semaphore with semctl() failed.");
27  }
28  } else if (errno == EEXIST) {
29  semid = semget(semkey, 1, 0600);
30  }
31  if (semid < 0) {
32  B2ERROR("Couldn't create semaphore with semget()! Maybe you have too many semaphores from aborted processes lying around, you can clean those up by running 'clear_basf2_ipc'.");
33  return semid;
34  }
35 
36  return semid;
37 }

◆ isLocked()

bool isLocked ( int  semId)
static

Return true if the given semaphore is locked.

If you know the lock might be held by the current process (e.g. while in a signal handler), locking is only safe if this returns false.

Definition at line 46 of file SemaphoreLocker.cc.

◆ lock()

void lock ( void  )

Lock the semaphore.

If the semaphore is locked, this function will block until it can acquire a lock.

Definition at line 72 of file SemaphoreLocker.cc.


The documentation for this class was generated from the following files: