I came up with a rule to never mess up in multi-threading:
The only interface function between threads is passing string data representing the data you want to give… Like a TCP/Ip or UDP packet
….Never deadlock
……….Never stamp on memory
………………No worries for the rest of your multithread career
………………………Jim’s multithread rule.
The reason it never deadlocks is because reading and writing take a finite amount of time and cannot be stopped unless the machine is malfunctioning.
The reason it never stamps on memory is that you do not read from a memory address that isn’t locked.
You can write to this address many times, with packets pooling up in an array buffer.
You can read and just exit if it is empty like you’re accepting an internet packet.
Why did everyone have so much trouble with threads back in the day? People thought they were tough or something. ;) Now you know the way.
If you choose to go fancy and do things a new way, there are times and places for it, but they’re extremely rare compared to just doing it this way, which is awesome if you can use multicores with it.
Psedo CODE:
Write:
1) Compile ‘thread A’ data into array of packet strings
2) Check if unlocked otherwise wait
3) lock
4) Append array of packet strings into an array of strings that only get accessed behind lock
5) Unlock
Read:
1) Check if unlocked otherwise wait
2) lock
3) read array of strings that only get accessed behind lock into an array local to ‘thread B’
4) unlock
5) decode packet like you would a video game data packet
It should be impossible to deadlock this on most systems, near impossible on the rest. I’m not sure if this is common knowledge or not, but this is the meat and potatoes way of doing things. It wasn’t easy to figure out, but it’s easy to use,applicable in close to 100% of multithread situations.