Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There should be a centralized place where task producers store new tasks, and from where task consumers take tasks to process them. The problem is a bit simpler if all tasks are produced before consumers begin their work. Your working threads are task consumers. Task is usually represented with one object that contains all relevant data needed to complete the task. Working thread should not have any form of Sleep, because it is not important which thread is faster and how many tasks it completes. Threads consume tasks in a loop as long as there are tasks to be consumed. This consuming is protected by some <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx" rel="nofollow">lock</a>.</p> <p>EDIT: I would propose the restructuring of code so that there is only one thread that does all the reading, in asynchronous way (<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread.aspx" rel="nofollow">BeginRead</a> or <a href="http://msdn.microsoft.com/en-us/library/hh137813.aspx" rel="nofollow">ReadAsync</a>). The code would start reading on each socket, and wait until some socket receives data or closes. If data are received for a socket <em>and data are complete</em> then produce new task. You must buffer incomplete data and read more until data are complete. When task is produced one task consumer should eventually pick up the task, process it and send the result to corresponding socket. So socket is read from in one thread and written to in several threads. To prevent some race conditions main reader thread must not read more data for specific socket if there is outstanding incomplete task produced for it. When task is completed main thread may start reading more data.</p> <p>I haven't covered all the corners, because that would produce a wall of text. Maybe there is a library that does all the communication for you, but I don't know any.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload