开发者

Non-block vs select() call in socket

开发者 https://www.devze.com 2023-01-16 21:10 出处:网络
I have to implement a game server in C which handles multiple开发者_开发问答 clients and continuously exchange information with them. The client may not be sending information at all times.Should I as

I have to implement a game server in C which handles multiple开发者_开发问答 clients and continuously exchange information with them. The client may not be sending information at all times.Should I assign a thread with non-blocking socket to them or use select() call.

Which one is better?


Both will work just as well in most cases. Note that the thread version will use blocking sockets, and the select-based uses non-blocking sockets. In the case of a server, you may feel that events for data received is a good model.

The threaded version will have the memory-overhead of allocating a stack for each thread (often the size of a page), but you can program as if you have only one client.

The evented version needs to maintain state between callbacks, which can be more work, but again, in servers it feels quite natural.


select() is the way to go, that's what it's made for. If you go for the threaded non-blocking approach, you will have to implement a sleep after each tick or the thread will use all available cpu time. So, the worst case response time, if one client is sending data, is your sleep value. You could also implement one thread per socket and make it blocking, but depending on how many sockets you have, that will be much overhead.

With select() you can watch all sockets at once (no matter if they are blocking or not, btw) and only have to process those which are active.

If you are on linux an have many sockets to watch, you can take a look at epoll()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号