Design Patterns for Multithreading [closed]

和自甴很熟 提交于 2019-12-03 14:58:53

问题


Multitasking seems to be a disaster at times when big projects crashes due to shared mutation of I would say shared resources are accessed by multiple threads. It becomes very difficult to debug and trace the origin of bug and what is causing it. It made me ask, are there any design patterns, which can be used while designing multithreaded programs?

I would really appreciate your views and comments on this and if someone can present good design practices which can be followed to make our program thread safe, it will be a great help.


回答1:


@WYSIWYG link seems to have a wealth of useful patterns but i can give you some guidelines to follow. The main source of problems with Multi-Threaded programs is Update Operations or Concurrent Modification and some of the less occurring problems are Starvation, Deadlocks , etc which are more deadly if i may say, so to avoid these situations you can:

  • Make use of the Immutable Object pattern, if an object can't be modified after creation then you can't have uncoordinated updates and as we know the creation operation itself is guaranteed to be atomic by the JVM in your case.
  • Command Query Segregation Principle: that is separate code that modifies the object from code that reads them because reading can happen concurrently but modification can't.
  • Take huge benefit of the language and library features you are using such as concurrent lists and threading structures because they are well designed and have good performance.
  • There is a book (although an old one) but with very good designs for such systems, it is called Concurrent Programming in Java.



回答2:


Design patterns are used to solve a specific problem. If you want to avoid deadlocks and increase debugging, there are some dos and donts

  1. User thread-safe library. .Net java, C++ have their own thread safe libraries. Use them. Don't try to create your own data structures.

  2. If you are using .Net, try Task instead of threads. They are more logical and safe.

You might wanna look at list of some Concurrency related patterns

http://www.cs.wustl.edu/~schmidt/patterns-ace.html



来源:https://stackoverflow.com/questions/17263335/design-patterns-for-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!