Krab
Krab

Reputation: 6756

uvlib for game server

I know there are some background threads and they executes IO operations etc. and after that, my callback is called. Is all callbacks called in one thread (= not two callbacks can be executed same time)? For example callback passed to uv_read_start (echo_read), that should be called, when data comes on socket connection. Is echo_read always called in main thread and those background threads are used only for buffering data from that socket? I want create game server with libuv, but actually i need to be sure, that there will be always just one game packet processed at a time and not more (otherwise there will be lot of sync issues and i will probably need to implement all from the ground).

int main() {
    loop = uv_default_loop();

    uv_tcp_t server;
    uv_tcp_init(loop, &server);

    struct sockaddr_in bind_addr = uv_ip4_addr("0.0.0.0", 7000);
    uv_tcp_bind(&server, bind_addr);
    int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
    if (r) {
        fprintf(stderr, "Listen error %s\n", uv_err_name(uv_last_error(loop)));
        return 1;
    }
    return uv_run(loop, UV_RUN_DEFAULT);
}

void on_new_connection(uv_stream_t *server, int status) {
    if (status == -1) {
        // error!
        return;
    }

    uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
    uv_tcp_init(loop, client);
    if (uv_accept(server, (uv_stream_t*) client) == 0) {
        uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
    }
    else {
        uv_close((uv_handle_t*) client, NULL);
    }
}

Upvotes: 1

Views: 1095

Answers (1)

Andrius Bentkus
Andrius Bentkus

Reputation: 1392

Yes, the libuv event loop guarantees that the processing of callbacks is done sequentially, not in parallel.

This is the key idea of event loops which makes them suitable for game engines, since you do not need to synchronize threads therefore avoiding the cost of the various locking mechanisms. If you make modifications to your data, they will be consistent on all other callbacks.

However, uv_run will run only on one core and with enough throughput it will be able only to make one core sweat.

If you are coding server code for a game which has a lot of connections (MMPORG) then you will need to create one thread per core and run the an uv event loop within each one. If we are talking about a game like counter strike, one event loop will be enough.

Upvotes: 1

Related Questions