Sha256: 91ebcfbfcd27db30688828fc52aa9f24284ea4369862d4b057db9ed972e6f350

Contents?: true

Size: 1.3 KB

Versions: 15

Compression:

Stored size: 1.3 KB

Contents

#include <stdio.h>
#include <uv.h>

uv_barrier_t blocker;
uv_rwlock_t numlock;
int shared_num;

void reader(void *n)
{
    int num = *(int *)n;
    int i;
    for (i = 0; i < 20; i++) {
        uv_rwlock_rdlock(&numlock);
        printf("Reader %d: acquired lock\n", num);
        printf("Reader %d: shared num = %d\n", num, shared_num);
        uv_rwlock_rdunlock(&numlock);
        printf("Reader %d: released lock\n", num);
    }
    uv_barrier_wait(&blocker);
}

void writer(void *n)
{
    int num = *(int *)n;
    int i;
    for (i = 0; i < 20; i++) {
        uv_rwlock_wrlock(&numlock);
        printf("Writer %d: acquired lock\n", num);
        shared_num++;
        printf("Writer %d: incremented shared num = %d\n", num, shared_num);
        uv_rwlock_wrunlock(&numlock);
        printf("Writer %d: released lock\n", num);
    }
    uv_barrier_wait(&blocker);
}

int main()
{
    uv_barrier_init(&blocker, 4);

    shared_num = 0;
    uv_rwlock_init(&numlock);

    uv_thread_t threads[3];

    int thread_nums[] = {1, 2, 1};
    uv_thread_create(&threads[0], reader, &thread_nums[0]);
    uv_thread_create(&threads[1], reader, &thread_nums[1]);

    uv_thread_create(&threads[2], writer, &thread_nums[2]);

    uv_barrier_wait(&blocker);
    uv_barrier_destroy(&blocker);

    uv_rwlock_destroy(&numlock);
    return 0;
}

Version data entries

15 entries across 15 versions & 2 rubygems

Version Path
mt-libuv-4.1.04 ext/libuv/docs/code/locks/main.c
mt-libuv-4.1.03 ext/libuv/docs/code/locks/main.c
mt-libuv-4.1.02 ext/libuv/docs/code/locks/main.c
libuv-4.0.9 ext/libuv/docs/code/locks/main.c
libuv-4.0.2 ext/libuv/docs/code/locks/main.c
libuv-4.0.1 ext/libuv/docs/code/locks/main.c
libuv-4.0.0 ext/libuv/docs/code/locks/main.c
libuv-3.3.0 ext/libuv/docs/code/locks/main.c
libuv-3.2.4 ext/libuv/docs/code/locks/main.c
libuv-3.2.3 ext/libuv/docs/code/locks/main.c
libuv-3.2.2 ext/libuv/docs/code/locks/main.c
libuv-3.2.1 ext/libuv/docs/code/locks/main.c
libuv-3.2.0 ext/libuv/docs/code/locks/main.c
libuv-3.1.9 ext/libuv/docs/code/locks/main.c
libuv-3.1.8 ext/libuv/docs/code/locks/main.c