Today I am back onto one of my favorite topics, as of late: multithreading and data integrity. I know, some of you are probably sick of this one, but today I thought about it from a totally different angle: responsibility and ethics. No, not whether or not using a thread is morally correct… but who is responsible for maintain thread safety? Specifically, the library/class/function/etc. programmer, or the programmer who uses it? Or, to put it another way, should we all write code with the assumption that it will be used in a multithreaded situation by code that does not do locking, or should we assume that if someone is going to be in a multithread scenario that it is up to them to handle locking, deadlocks, etc?
This is actually quite a thorny situation!
For one thing, making code thread safe is easier to do as granularly as possible at the lowest levels. Think about it: what makes more sense, the class designer using the appropriate systems only where absolutely needed, or the person using the class trying to figure out what needs locking and deadlock prevention and so on? What usually ends up happening if a class (or function, etc.) is not marked as thread safe is that the person using it grabs an exclusive lock on the item in question every time they touch it within a thread, following the Aliens philosophy: “It’s the only way to be sure.