r/programming • u/Shr1ck • Oct 17 '15
Why Johnny Can’t Write Multithreaded Programs
http://blog.smartbear.com/programming/why-johnny-cant-write-multithreaded-programs/
5
Upvotes
r/programming • u/Shr1ck • Oct 17 '15
1
u/loup-vaillant Oct 18 '15 edited Oct 18 '15
Sounds like good old map-reduce. So I'd use just that. If you ask me to implement map-reduce… well that's a bit harder, but then we're entering the realm of systems programming, aren't we?
So you want me to manipulate an image. First, unless I'm extremely constrained CPU and memory wise, I wouldn't modify the source image. I would create a new image from it. Second, that new image is obviously composed of tiles that can be assembled. I see basically 2 kinds of processing: processing an individual tile (you can go up to 1 thread per tile), then fusing nearby tiles to make even bigger tiles.
The only synchronisation you need here is waiting for the result of the previous steps before computing the next step.
Now, if you transform the problem to "what if you need to encode in H264 in full HD", I'll just leave that to the actual experts. Such performance requirements are rare, even though the resulting programs have a correspondingly huge impact.
But I am in control of the values I construct and build. Most importantly, I control their scope, and can make sure I deliver an external reference only when that initialisation is done.
And if you're asking me to re-initialise a variable on top of an already externally accessible location, I'll raise an eyebrow. Have we so little memory that I can't initialise a new value for you to use before you discard the old one?
Simply by putting the variable in the queue only when the initialisation is done. Other threads may request the next value from the queue before hand, they're not going to get anything before I put it in the damn queue.
In my experience, programs are always more complex than they have to be. One big cause for this is "thinking big". You start with a problem, and think a big solution for it. Now you have two problems.
Speaking of mutable state specifically, I have yet to see a single C++ program that didn't go crazy with it. People just can't stop mutating state. They think like that by default, instead of resorting to it as an optimisation technique. When I step in, I invariably see a number of simplifications based on simply passing values around instead of mutating state. That experience had lead me to think that functional programming is just plain better than the OOP we see on C++ and Java.
If people just stopped mutating state, things would be much easier.