1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2011 New Dream Network
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
15 #include "cross_process_sem.h"
18 #include <semaphore.h>
22 /* We put our cross-process semaphore into a page of memory mapped with mmap. */
23 struct cross_process_sem_data_t
28 /* A factory function is a good choice here because we want to be able to
29 * return an error code. It does force heap allocation, but that is the
30 * easiest way to use synchronization primitives anyway. Most programmers don't
31 * care about destroying semaphores before the process finishes. It's pretty
32 * difficult to get it right and there is usually no benefit.
35 create(int initial_val, CrossProcessSem** res)
37 struct cross_process_sem_data_t *data = static_cast < cross_process_sem_data_t*> (
38 mmap(NULL, sizeof(struct cross_process_sem_data_t),
39 PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0));
40 if (data == MAP_FAILED) {
44 int ret = sem_init(&data->sem, 1, initial_val);
48 *res = new CrossProcessSem(data);
55 munmap(m_data, sizeof(struct cross_process_sem_data_t));
59 void CrossProcessSem::
63 int ret = sem_wait(&m_data->sem);
73 void CrossProcessSem::
76 int ret = sem_post(&m_data->sem);
88 if (sem_getvalue(&m_data->sem, &cval) == -1)
91 int diff = dval - cval;
92 for (int i = 0; i < diff; ++i)
93 sem_post(&m_data->sem);
96 int diff = cval - dval;
97 for (int i = 0; i < diff; ++i)
98 sem_wait(&m_data->sem);
104 CrossProcessSem(struct cross_process_sem_data_t *data)