So, i have a situation where an event occurs and i need to then 'broadcast' that to several subscribed 'listeners'.
My current design is a loop for each subscriber and works serially, notifying each 'receiver' in turn.
However, in some load/stress testing i find that it can queue up more than i like in that #15 in a list of receivers could end up waiting a long time before it receives it's notification.
I want to provide a way to have the list of receivers receive the notification more or less concurrently.
ThreadPool is out. I have my own reasons as to开发者_开发技巧 why.
My concern is on performance. Here is what I'm considering....
A. Each time the event fires, one thread is created for each receiver to do the receiver specific notification. The thread dies when the notification completes.
----OR---- B. The first time the event fires, a thread is created for each receiver, but is an 'infinite' thread (has a loop that keeps it alive), and notification details are marshaled to each of these threads which then process the new data.So, the question is: Is it more expensive to create a new thread, or to marshal data to an existing thread, or if equally expensive, why choose one over the other?
Creating a thread instead of using a TP thread is quite expensive, both in system resources and time. Passing data through, say, a thread-safe queue can be performant, provided you haven't maxed out the available cores (which sounds very likely) and the receiving thread is blocking on a synchronization object that you signal. Typical thread context switch cost is between 2000 and 10,000 machine cycles, you are probably on the low end since the thread runs in the same address space.
The real cost is the difficulty of getting so many threads to run correctly without endlessly chasing races and deadlocks.
Doesn't your loop create a busy waiting problem? Most of the loop's iterations are going to waste CPU cycles since they don't do anything productive, except a couple of checks that you have in the loop. I would probably stick to new thread since having an idle CPU is always a bad performance choice.
P.S. Are you implementing some sort of a leader election algorithm?
精彩评论