Ejemplo n.º 1
0
THREAD_FUNC(print_hello, param) {
    context_t* ctx = param;

    for (;;) {
        SLEEP(rand() % 5);
        printf("%d is hungry!\n", ctx->id);

        if (ctx->id % 2) {
            // Pick Up Right Before Left
            if (MUTEX_TRYLOCK(*ctx->right_chopstick)) {
                printf("%d got right chopstick\n", ctx->id);
            } else {
                printf("%d couldn't get right chopstick, will try later\n", ctx->id);
                continue;
            }

            if (MUTEX_TRYLOCK(*ctx->left_chopstick)) {
                printf("%d got left chopstick\n", ctx->id);
            } else {
                printf("%d couldn't get left chopstick, will try later\n", ctx->id);
                MUTEX_UNLOCK(*ctx->right_chopstick);
                printf("%d release right chopstick\n", ctx->id);
                continue;
            }
        } else {
            // Pick Up Left Before Right
            if (MUTEX_TRYLOCK(*ctx->left_chopstick)) {
                printf("%d got left chopstick\n", ctx->id);
            } else {
                printf("%d couldn't get left chopstick, will try later\n", ctx->id);
                continue;
            }

            if (MUTEX_TRYLOCK(*ctx->right_chopstick)) {
                printf("%d got right chopstick\n", ctx->id);
            } else {
                printf("%d couldn't get right chopstick, will try later\n", ctx->id);
                MUTEX_UNLOCK(*ctx->left_chopstick);
                printf("%d release left chopstick\n", ctx->id);
                continue;
            }

        }


        printf("%d start eating\n", ctx->id);
        SLEEP(1);
        printf("%d finish eating\n", ctx->id);

        MUTEX_UNLOCK(*ctx->right_chopstick);
        printf("%d release right chopstick\n", ctx->id);
        MUTEX_UNLOCK(*ctx->left_chopstick);
        printf("%d release left chopstick\n", ctx->id);
    }

    free(ctx);
    return 0;
}
Ejemplo n.º 2
0
ConnMgr::status_t ConnMgr::trylock()
{
    int rc = MUTEX_TRYLOCK(&mapMutex);
    if (rc == 0)
        return SUCCESS;
    if (rc == EDEADLK)
        return ERR_LOCK_AOWNED;
    if (rc == EBUSY)
        return ERR_LOCK_BUSY;
    return ERR_LOCK;
}