Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a non-thread-safe component with a multithread component (Design)

Design problem :

Using a non-thread-safe component (Collection, API, ...) in/with a multithread component ...

Example :

component1 : A multithread socket server who send messages ... to a message handler

component2 : A non-thread-safe message handler who process messages ... from a server

My solution :

Adding a thread-safe component ( buffer ) between the server and the message handler, the buffer will receive messages in multithread manner from the server and send them in the same order to the message handler in a single thread manner.

My question :

Is there a better solution ? an appropriate design pattern may be proxy or pipeline ?

like image 691
wj. Avatar asked Mar 28 '26 22:03

wj.


1 Answers

One very nice option for this is to use a Producer/Consumer pattern.

In this case, the multithreaded sockets can act as multiple producers into a guarded buffer, and your non-threadsafe message handler can consume messages in its own thread, completely synchronously. This provides a very clean way to handle this type of scenario.

like image 86
Reed Copsey Avatar answered Mar 31 '26 09:03

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!