summaryrefslogtreecommitdiff
path: root/ext/-test-/gvl/call_without_gvl/call_without_gvl.c
blob: 654c979479a60401d26f169c0f3d25307d90253d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "ruby/ruby.h"
#include "ruby/thread.h"

static void*
native_sleep_callback(void *data)
{
    struct timeval *timeval = data;
    select(0, NULL, NULL, NULL, timeval);

    return NULL;
}


static VALUE
thread_runnable_sleep(VALUE thread, VALUE timeout)
{
    struct timeval timeval;

    if (NIL_P(timeout)) {
	rb_raise(rb_eArgError, "timeout must be non nil");
    }

    timeval = rb_time_interval(timeout);

    rb_thread_call_without_gvl(native_sleep_callback, &timeval, RUBY_UBF_IO, NULL);

    return thread;
}

struct loop_ctl {
    int notify_fd;
    volatile int stop;
};

static void *
do_loop(void *p)
{
    struct loop_ctl *ctl = p;

    /* tell the waiting process they can interrupt us, now */
    write(ctl->notify_fd, "", 1);

    while (!ctl->stop) {
        struct timeval tv = { 0, 10000 };
        select(0, NULL, NULL, NULL, &tv);
    }
    return 0;
}

static void
stop_set(void *p)
{
    struct loop_ctl *ctl = p;

    ctl->stop = 1;
}

static VALUE
thread_ubf_async_safe(VALUE thread, VALUE notify_fd)
{
    struct loop_ctl ctl;

    ctl.notify_fd = NUM2INT(notify_fd);
    ctl.stop = 0;

    rb_nogvl(do_loop, &ctl, stop_set, &ctl, RB_NOGVL_UBF_ASYNC_SAFE);
    return thread;
}

void
Init_call_without_gvl(void)
{
    rb_define_method(rb_cThread, "__runnable_sleep__", thread_runnable_sleep, 1);
    rb_define_method(rb_cThread, "__ubf_async_safe__", thread_ubf_async_safe, 1);
}