Which kind of multiple threads program we need to write

Table of Contents

SUMMARY

I think about this for a long time, and I have read lots of programs, which contain single thread or multiple threads. In my  opinion, some of them are not very good, that is why I write this blog.

SINGLE THREAD

Single thread program is simple for us, there is no lock to care, at most we only need to care about asynchronous call.  And we can provide a high performance program.

MULTIPLE THREADS

Multiple threads program is hard for us, there are lots of locks to care, we need to process them carefully, it’ll crash or dead lock when even one case of a wrong way to use lock. So, normally we need to do lots of efforts to debug and fix the bugs. Other wise, it maybe provide more performance than single program. Actually I said “maybe“, you know there is no free lunch in many scenes, that means we can’t get satisfied with the results normally.

WHY

I know many guys can not approve that, you maybe believe that multiple threads program can be really better than single one. Ok, we need to make a deep thinking, Does the multiple threads program just only add some threads into program simply? And you think the performance will be grow up simply? The answer is obviously not. We know in many scenes we need to use the lock to synchronous our logic, whose resources share with other threads at the same time. When we entry the lock, the program will transfer to a single type program, so the performance will fall down, it will be even worse than the single thread one because of the lock call.

You may say “there are lots of lock type suck as Read-Write Lock”. Yes, but read-write lock is only used for some special cases, and usually these cases are very limited.

So the scene if you can separate logic into independence parts, that’s a good scene and design. but if you can not separate completely, maybe you need to figure it out whether you should do it. For the second one, you may use lots of lock to protect your program for running well, but it’ll make it too complex and risk.

But, another scene you can use multiple threads simply, that’s when your program has more than one part, and these parts are not the same functional, and then you can connect them easily, such as one producer one consumer model.

CONCLUSION

Ok, now you know whether you can decide what kind of program you need to use multiple threads.

  • When the parts of program is the independence.
  • one producer one consumer model.

For other case, you need to figure it out and redesign for make the parts of your program independence.