Friday, October 13, 2006

Threads!

Every time I use threads I wish I hadn't! IMHO they exponentially multiply any problems you might have in code and often far outweight their benefit.

My latest bugbear (which I've come across before but not learnt my lesson) is "accidentally" using different threads to read incoming bytes from a scoket. Obviously this is a big mistake as the ordering of bytes is critical, so if you've got two threads reading the bytes, god-knows which thread is going to read which btye.

My first mistake was to create a new form which read some bytes; I temporarily forgot that forms run in their own thread, so my comms broke down until I spotted this.

My next mistake was to forget how quick computers are. Instead of the form using its own thread, the main thread waits until the form disappears and then reads the bytes after that. However, a split second before that my main game loop is started, which also reads incoming bytes. In the 100th of a second between the form being closed and the main thread realising that the form has been closed, my main game loop starts reading in bytes itself and causing chaos.

I know I should have a single sycnhronized method to do this, but there's loads of code to change. Suggestions welcome.

No comments: