Blocking + threads vs. non-blocking

Started by
19 comments, last by Promit 20 years, 1 month ago
Yes, most games will use threads for several common things:

1) sound -- DirectSound will start some for you, if nothing else
2) non-blocking I/O -- because overlapped I/O does not exist on Win9x/ME, you have to emulate it with threads
3) non-blocking DNS resolution -- gethostbyname() is blocking, you usually want to make it async with a thread

However, in all these cases, the thread is NOT involved in step-by-step operations within the game. If you involve more than one thread for each step or frame of your game, then you need to pay synchronization overhead, which is 1-2 microseconds for an UNCONTENDED critical section (because of the PCI bus and the x86 memory model, so it doesn''t improve with hardware), and 10-20 microseconds for a blocking kernel primitive (depending on OS and CPU speed).

Maybe you think it makes sense to have one thread which reads from a socket, and posts messages into an incoming queue (while locking the queue), and then have the game lock the queue and pull data out each step. However, this doesn''t really buy you anything above just using select() or non-blocking sockets, and it costs you the interlock. Also, if you have a shared lock, then one thread (say, the network read) may be pre-empted with the lock held, and the other thread will wait until the network thread can be scheduled again and release the lock.

Threads really aren''t the end-all of everything; you should only use them when you have to, for performance AND correctness reasons.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement