0

in the libev ,I have initilized the io watcher to catch events and this event causes to store certain value in some cache. I have another timer watcher which runs every 10 sec, reads the cache value. In such case I suppose there is a race condition. do I need to use lock in two different libev watcher or libev handles it.

eg:

 TCP_CACHE_TIMEOUT = g_hash_table_new_full(g_str_hash, g_int_equal, key_destroy_cb, value_destroy_timeoutcb);
    zlog_info(_c,"TCP Server started at _port: %d",_port);
    int fd =setup_tcp_socket(_port);
    if(fd<0)
    {
        return NULL;
    }

    struct ev_loop *loop = EV_DEFAULT;

    struct _sock_ev_serv server;
    server.fd = fd;
    ev_io_init(&server.io, event_server, server.fd, EV_READ);
    ev_io_start(EV_A_ &server.io);

    ev_timer_init (&timeout_watcher, timeout_idle_fd, 0, 10.);
    ev_timer_again (loop,&timeout_watcher);

    ev_loop(loop, 0);  

here I have loop and initilizes io watcher to accept server event, and timer watcher to look in the cache every 10 sec. In such case Do I need to handle the race condition myself or the two watcher io and timer running time is managed by libev?

user5335302
  • 449
  • 1
  • 5
  • 11

1 Answers1

1

Short answer: There is no race condition, you don't need a lock.

Longer answer:
The reason that there is no race condition, is because libev is in a loop checking the io watcher, then the timer, then the io, then the timer.....
Whichever one is triggered first, is run first. There is no overlap between the two callbacks.

If however, you were using a threaded event loop (possible, but unlikely judging by your code), and you were reading from the same file in two different threads, then there would be a race condition and you would need a lock.

Example:
If you get data in the io watcher after 0.9 seconds, and your callback for that watcher takes 0.2 seconds to run, your timer will be invoked after the io callback has already finished (at ~10.1 seconds).