semaphore.c 16.7 KB
Newer Older
1 2 3 4 5
/*
 * A type which wraps a semaphore
 *
 * semaphore.c
 *
6 7
 * Copyright (c) 2006-2008, R Oudkerk
 * Licensed to PSF under a Contributor Agreement.
8 9 10 11 12 13 14
 */

#include "multiprocessing.h"

enum { RECURSIVE_MUTEX, SEMAPHORE };

typedef struct {
15 16 17 18 19 20
    PyObject_HEAD
    SEM_HANDLE handle;
    long last_tid;
    int count;
    int maxvalue;
    int kind;
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
} SemLockObject;

#define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid)


#ifdef MS_WINDOWS

/*
 * Windows definitions
 */

#define SEM_FAILED NULL

#define SEM_CLEAR_ERROR() SetLastError(0)
#define SEM_GET_LAST_ERROR() GetLastError()
#define SEM_CREATE(name, val, max) CreateSemaphore(NULL, val, max, NULL)
#define SEM_CLOSE(sem) (CloseHandle(sem) ? 0 : -1)
#define SEM_GETVALUE(sem, pval) _GetSemaphoreValue(sem, pval)
#define SEM_UNLINK(name) 0

static int
_GetSemaphoreValue(HANDLE handle, long *value)
{
44 45 46 47 48 49 50 51 52 53 54 55 56 57
    long previous;

    switch (WaitForSingleObject(handle, 0)) {
    case WAIT_OBJECT_0:
        if (!ReleaseSemaphore(handle, 1, &previous))
            return MP_STANDARD_ERROR;
        *value = previous + 1;
        return 0;
    case WAIT_TIMEOUT:
        *value = 0;
        return 0;
    default:
        return MP_STANDARD_ERROR;
    }
58 59 60 61 62
}

static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
63 64 65
    int blocking = 1;
    double timeout;
    PyObject *timeout_obj = Py_None;
66 67
    DWORD res, full_msecs, nhandles;
    HANDLE handles[2], sigint_event;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    static char *kwlist[] = {"block", "timeout", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
                                     &blocking, &timeout_obj))
        return NULL;

    /* calculate timeout */
    if (!blocking) {
        full_msecs = 0;
    } else if (timeout_obj == Py_None) {
        full_msecs = INFINITE;
    } else {
        timeout = PyFloat_AsDouble(timeout_obj);
        if (PyErr_Occurred())
            return NULL;
        timeout *= 1000.0;      /* convert to millisecs */
        if (timeout < 0.0) {
            timeout = 0.0;
        } else if (timeout >= 0.5 * INFINITE) { /* 25 days */
            PyErr_SetString(PyExc_OverflowError,
                            "timeout is too large");
            return NULL;
        }
        full_msecs = (DWORD)(timeout + 0.5);
    }

    /* check whether we already own the lock */
    if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
        ++self->count;
        Py_RETURN_TRUE;
    }

101
    /* check whether we can acquire without releasing the GIL and blocking */
102 103 104 105 106 107
    if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
        self->last_tid = GetCurrentThreadId();
        ++self->count;
        Py_RETURN_TRUE;
    }

108 109 110 111 112 113 114 115
    /* prepare list of handles */
    nhandles = 0;
    handles[nhandles++] = self->handle;
    if (_PyOS_IsMainThread()) {
        sigint_event = _PyOS_SigintEvent();
        assert(sigint_event != NULL);
        handles[nhandles++] = sigint_event;
    }
116

117 118 119
    /* do the wait */
    Py_BEGIN_ALLOW_THREADS
    if (sigint_event != NULL)
120
        ResetEvent(sigint_event);
121 122
    res = WaitForMultipleObjects(nhandles, handles, FALSE, full_msecs);
    Py_END_ALLOW_THREADS
123 124 125 126 127

    /* handle result */
    switch (res) {
    case WAIT_TIMEOUT:
        Py_RETURN_FALSE;
128
    case WAIT_OBJECT_0 + 0:
129 130 131
        self->last_tid = GetCurrentThreadId();
        ++self->count;
        Py_RETURN_TRUE;
132 133 134
    case WAIT_OBJECT_0 + 1:
        errno = EINTR;
        return PyErr_SetFromErrno(PyExc_IOError);
135 136 137 138 139 140 141 142
    case WAIT_FAILED:
        return PyErr_SetFromWindowsErr(0);
    default:
        PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
                     "WaitForMultipleObjects() gave unrecognized "
                     "value %d", res);
        return NULL;
    }
143 144 145 146 147
}

static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    if (self->kind == RECURSIVE_MUTEX) {
        if (!ISMINE(self)) {
            PyErr_SetString(PyExc_AssertionError, "attempt to "
                            "release recursive lock not owned "
                            "by thread");
            return NULL;
        }
        if (self->count > 1) {
            --self->count;
            Py_RETURN_NONE;
        }
        assert(self->count == 1);
    }

    if (!ReleaseSemaphore(self->handle, 1, NULL)) {
        if (GetLastError() == ERROR_TOO_MANY_POSTS) {
            PyErr_SetString(PyExc_ValueError, "semaphore or lock "
                            "released too many times");
            return NULL;
        } else {
            return PyErr_SetFromWindowsErr(0);
        }
    }

    --self->count;
    Py_RETURN_NONE;
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
}

#else /* !MS_WINDOWS */

/*
 * Unix definitions
 */

#define SEM_CLEAR_ERROR()
#define SEM_GET_LAST_ERROR() 0
#define SEM_CREATE(name, val, max) sem_open(name, O_CREAT | O_EXCL, 0600, val)
#define SEM_CLOSE(sem) sem_close(sem)
#define SEM_GETVALUE(sem, pval) sem_getvalue(sem, pval)
#define SEM_UNLINK(name) sem_unlink(name)

189
#ifndef HAVE_SEM_UNLINK
190 191 192
#  define sem_unlink(name) 0
#endif

193
#ifndef HAVE_SEM_TIMEDWAIT
194 195 196 197 198
#  define sem_timedwait(sem,deadline) sem_timedwait_save(sem,deadline,_save)

int
sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
{
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    int res;
    unsigned long delay, difference;
    struct timeval now, tvdeadline, tvdelay;

    errno = 0;
    tvdeadline.tv_sec = deadline->tv_sec;
    tvdeadline.tv_usec = deadline->tv_nsec / 1000;

    for (delay = 0 ; ; delay += 1000) {
        /* poll */
        if (sem_trywait(sem) == 0)
            return 0;
        else if (errno != EAGAIN)
            return MP_STANDARD_ERROR;

        /* get current time */
        if (gettimeofday(&now, NULL) < 0)
            return MP_STANDARD_ERROR;

        /* check for timeout */
        if (tvdeadline.tv_sec < now.tv_sec ||
            (tvdeadline.tv_sec == now.tv_sec &&
             tvdeadline.tv_usec <= now.tv_usec)) {
            errno = ETIMEDOUT;
            return MP_STANDARD_ERROR;
        }

        /* calculate how much time is left */
        difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
            (tvdeadline.tv_usec - now.tv_usec);

        /* check delay not too long -- maximum is 20 msecs */
        if (delay > 20000)
            delay = 20000;
        if (delay > difference)
            delay = difference;

        /* sleep */
        tvdelay.tv_sec = delay / 1000000;
        tvdelay.tv_usec = delay % 1000000;
        if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
            return MP_STANDARD_ERROR;

        /* check for signals */
        Py_BLOCK_THREADS
        res = PyErr_CheckSignals();
        Py_UNBLOCK_THREADS

        if (res) {
            errno = EINTR;
            return MP_EXCEPTION_HAS_BEEN_SET;
        }
    }
252 253 254 255 256 257 258
}

#endif /* !HAVE_SEM_TIMEDWAIT */

static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
259
    int blocking = 1, res, err = 0;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    double timeout;
    PyObject *timeout_obj = Py_None;
    struct timespec deadline = {0};
    struct timeval now;
    long sec, nsec;

    static char *kwlist[] = {"block", "timeout", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
                                     &blocking, &timeout_obj))
        return NULL;

    if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
        ++self->count;
        Py_RETURN_TRUE;
    }

    if (timeout_obj != Py_None) {
        timeout = PyFloat_AsDouble(timeout_obj);
        if (PyErr_Occurred())
            return NULL;
        if (timeout < 0.0)
            timeout = 0.0;

        if (gettimeofday(&now, NULL) < 0) {
            PyErr_SetFromErrno(PyExc_OSError);
            return NULL;
        }
        sec = (long) timeout;
        nsec = (long) (1e9 * (timeout - sec) + 0.5);
        deadline.tv_sec = now.tv_sec + sec;
        deadline.tv_nsec = now.tv_usec * 1000 + nsec;
        deadline.tv_sec += (deadline.tv_nsec / 1000000000);
        deadline.tv_nsec %= 1000000000;
    }

    do {
        Py_BEGIN_ALLOW_THREADS
        if (blocking && timeout_obj == Py_None)
            res = sem_wait(self->handle);
        else if (!blocking)
            res = sem_trywait(self->handle);
        else
            res = sem_timedwait(self->handle, &deadline);
        Py_END_ALLOW_THREADS
305
        err = errno;
306 307 308 309 310
        if (res == MP_EXCEPTION_HAS_BEEN_SET)
            break;
    } while (res < 0 && errno == EINTR && !PyErr_CheckSignals());

    if (res < 0) {
311
        errno = err;
312 313 314 315 316 317 318 319 320 321 322 323
        if (errno == EAGAIN || errno == ETIMEDOUT)
            Py_RETURN_FALSE;
        else if (errno == EINTR)
            return NULL;
        else
            return PyErr_SetFromErrno(PyExc_OSError);
    }

    ++self->count;
    self->last_tid = PyThread_get_thread_ident();

    Py_RETURN_TRUE;
324 325 326 327 328
}

static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
329 330 331 332 333 334 335 336 337 338 339 340 341
    if (self->kind == RECURSIVE_MUTEX) {
        if (!ISMINE(self)) {
            PyErr_SetString(PyExc_AssertionError, "attempt to "
                            "release recursive lock not owned "
                            "by thread");
            return NULL;
        }
        if (self->count > 1) {
            --self->count;
            Py_RETURN_NONE;
        }
        assert(self->count == 1);
    } else {
342
#ifdef HAVE_BROKEN_SEM_GETVALUE
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        /* We will only check properly the maxvalue == 1 case */
        if (self->maxvalue == 1) {
            /* make sure that already locked */
            if (sem_trywait(self->handle) < 0) {
                if (errno != EAGAIN) {
                    PyErr_SetFromErrno(PyExc_OSError);
                    return NULL;
                }
                /* it is already locked as expected */
            } else {
                /* it was not locked so undo wait and raise  */
                if (sem_post(self->handle) < 0) {
                    PyErr_SetFromErrno(PyExc_OSError);
                    return NULL;
                }
                PyErr_SetString(PyExc_ValueError, "semaphore "
                                "or lock released too many "
                                "times");
                return NULL;
            }
        }
364
#else
365 366 367 368 369 370 371 372 373 374 375
        int sval;

        /* This check is not an absolute guarantee that the semaphore
           does not rise above maxvalue. */
        if (sem_getvalue(self->handle, &sval) < 0) {
            return PyErr_SetFromErrno(PyExc_OSError);
        } else if (sval >= self->maxvalue) {
            PyErr_SetString(PyExc_ValueError, "semaphore or lock "
                            "released too many times");
            return NULL;
        }
376
#endif
377
    }
378

379 380
    if (sem_post(self->handle) < 0)
        return PyErr_SetFromErrno(PyExc_OSError);
381

382 383
    --self->count;
    Py_RETURN_NONE;
384 385 386 387 388 389 390 391 392 393 394
}

#endif /* !MS_WINDOWS */

/*
 * All platforms
 */

static PyObject *
newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue)
{
395 396 397 398 399 400 401 402 403 404 405
    SemLockObject *self;

    self = PyObject_New(SemLockObject, type);
    if (!self)
        return NULL;
    self->handle = handle;
    self->kind = kind;
    self->count = 0;
    self->last_tid = 0;
    self->maxvalue = maxvalue;
    return (PyObject*)self;
406 407 408 409 410
}

static PyObject *
semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
411 412 413 414 415 416
    char buffer[256];
    SEM_HANDLE handle = SEM_FAILED;
    int kind, maxvalue, value;
    PyObject *result;
    static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
    static int counter = 0;
417

418 419 420
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
                                     &kind, &value, &maxvalue))
        return NULL;
421

422 423 424 425
    if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
        PyErr_SetString(PyExc_ValueError, "unrecognized kind");
        return NULL;
    }
426

427
    PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%d", (long)getpid(), counter++);
428

429 430 431 432 433
    SEM_CLEAR_ERROR();
    handle = SEM_CREATE(buffer, value, maxvalue);
    /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
    if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
        goto failure;
434

435 436
    if (SEM_UNLINK(buffer) < 0)
        goto failure;
437

438 439 440
    result = newsemlockobject(type, handle, kind, maxvalue);
    if (!result)
        goto failure;
441

442
    return result;
443 444

  failure:
445 446 447 448
    if (handle != SEM_FAILED)
        SEM_CLOSE(handle);
    mp_SetError(NULL, MP_STANDARD_ERROR);
    return NULL;
449 450 451 452 453
}

static PyObject *
semlock_rebuild(PyTypeObject *type, PyObject *args)
{
454 455
    SEM_HANDLE handle;
    int kind, maxvalue;
456

457 458 459
    if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
                          &handle, &kind, &maxvalue))
        return NULL;
460

461
    return newsemlockobject(type, handle, kind, maxvalue);
462 463 464 465 466
}

static void
semlock_dealloc(SemLockObject* self)
{
467 468 469
    if (self->handle != SEM_FAILED)
        SEM_CLOSE(self->handle);
    PyObject_Del(self);
470 471 472 473 474
}

static PyObject *
semlock_count(SemLockObject *self)
{
475
    return PyLong_FromLong((long)self->count);
476 477 478 479 480
}

static PyObject *
semlock_ismine(SemLockObject *self)
{
481 482
    /* only makes sense for a lock */
    return PyBool_FromLong(ISMINE(self));
483 484 485 486 487
}

static PyObject *
semlock_getvalue(SemLockObject *self)
{
488
#ifdef HAVE_BROKEN_SEM_GETVALUE
489 490
    PyErr_SetNone(PyExc_NotImplementedError);
    return NULL;
491
#else
492 493 494 495 496 497 498
    int sval;
    if (SEM_GETVALUE(self->handle, &sval) < 0)
        return mp_SetError(NULL, MP_STANDARD_ERROR);
    /* some posix implementations use negative numbers to indicate
       the number of waiting threads */
    if (sval < 0)
        sval = 0;
499
    return PyLong_FromLong((long)sval);
500 501 502 503 504 505
#endif
}

static PyObject *
semlock_iszero(SemLockObject *self)
{
506
#ifdef HAVE_BROKEN_SEM_GETVALUE
507 508 509 510 511 512 513 514 515
    if (sem_trywait(self->handle) < 0) {
        if (errno == EAGAIN)
            Py_RETURN_TRUE;
        return mp_SetError(NULL, MP_STANDARD_ERROR);
    } else {
        if (sem_post(self->handle) < 0)
            return mp_SetError(NULL, MP_STANDARD_ERROR);
        Py_RETURN_FALSE;
    }
516
#else
517 518 519 520
    int sval;
    if (SEM_GETVALUE(self->handle, &sval) < 0)
        return mp_SetError(NULL, MP_STANDARD_ERROR);
    return PyBool_FromLong((long)sval == 0);
521 522 523 524 525 526
#endif
}

static PyObject *
semlock_afterfork(SemLockObject *self)
{
527 528
    self->count = 0;
    Py_RETURN_NONE;
529 530 531 532 533 534 535
}

/*
 * Semaphore methods
 */

static PyMethodDef semlock_methods[] = {
536 537 538 539
    {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
     "acquire the semaphore/lock"},
    {"release", (PyCFunction)semlock_release, METH_NOARGS,
     "release the semaphore/lock"},
Jesse Noller's avatar
Jesse Noller committed
540
    {"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
     "enter the semaphore/lock"},
    {"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
     "exit the semaphore/lock"},
    {"_count", (PyCFunction)semlock_count, METH_NOARGS,
     "num of `acquire()`s minus num of `release()`s for this process"},
    {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
     "whether the lock is owned by this thread"},
    {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
     "get the value of the semaphore"},
    {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
     "returns whether semaphore has value zero"},
    {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
     ""},
    {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
     "rezero the net acquisition count after fork()"},
    {NULL}
557 558 559 560 561 562 563
};

/*
 * Member table
 */

static PyMemberDef semlock_members[] = {
564 565 566 567 568 569 570
    {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
     ""},
    {"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
     ""},
    {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
     ""},
    {NULL}
571 572 573 574 575 576 577
};

/*
 * Semaphore type
 */

PyTypeObject SemLockType = {
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    PyVarObject_HEAD_INIT(NULL, 0)
    /* tp_name           */ "_multiprocessing.SemLock",
    /* tp_basicsize      */ sizeof(SemLockObject),
    /* tp_itemsize       */ 0,
    /* tp_dealloc        */ (destructor)semlock_dealloc,
    /* tp_print          */ 0,
    /* tp_getattr        */ 0,
    /* tp_setattr        */ 0,
    /* tp_reserved       */ 0,
    /* tp_repr           */ 0,
    /* tp_as_number      */ 0,
    /* tp_as_sequence    */ 0,
    /* tp_as_mapping     */ 0,
    /* tp_hash           */ 0,
    /* tp_call           */ 0,
    /* tp_str            */ 0,
    /* tp_getattro       */ 0,
    /* tp_setattro       */ 0,
    /* tp_as_buffer      */ 0,
    /* tp_flags          */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    /* tp_doc            */ "Semaphore/Mutex type",
    /* tp_traverse       */ 0,
    /* tp_clear          */ 0,
    /* tp_richcompare    */ 0,
    /* tp_weaklistoffset */ 0,
    /* tp_iter           */ 0,
    /* tp_iternext       */ 0,
    /* tp_methods        */ semlock_methods,
    /* tp_members        */ semlock_members,
    /* tp_getset         */ 0,
    /* tp_base           */ 0,
    /* tp_dict           */ 0,
    /* tp_descr_get      */ 0,
    /* tp_descr_set      */ 0,
    /* tp_dictoffset     */ 0,
    /* tp_init           */ 0,
    /* tp_alloc          */ 0,
    /* tp_new            */ semlock_new,
616
};