Multi Threading, safe code?
Author |
Message |
mirhagk
|
Posted: Thu Jun 09, 2011 6:41 am Post subject: Multi Threading, safe code? |
|
|
If I have a stack of "tasks", and I spawn a couple threads to update those tasks, will the code be thread-safe? The only time the threads merge is when they pop from the stack, can I be sure they won't both pop at the same time or something? Or do I need to use some locks and such?
I'm using C# btw, if it matters at all, with the built in stack. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
mirhagk
|
Posted: Thu Jun 09, 2011 6:56 pm Post subject: RE:Multi Threading, safe code? |
|
|
Also I noticed while testing threading code, I noticed the optimal number of threads (least time taken) was 16, which I don't get because I have a dual core with only a single thread each. |
|
|
|
|
|
DemonWasp
|
Posted: Thu Jun 09, 2011 10:38 pm Post subject: RE:Multi Threading, safe code? |
|
|
Since the order that tasks are removed from this stack (queue?) is irrelevant, the only concern is to make sure that you're using a thread-safe version of your stack object. You could read the Thread Safety section of the API here: http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx
The reason that the optimal time will be a number of threads greater than your CPU count has to do with O/S-level task scheduling and how that interacts with the hardware, and is a decidedly nontrivial discussion. There are a lot of tradeoffs you can make between number of threads, amount of memory consumed, time spent waiting to start, time taken to complete, and total throughput, and it's mostly left to experimentation to figure out what works best for your program (at least, for the moment). |
|
|
|
|
|
mirhagk
|
Posted: Tue Jun 14, 2011 8:33 pm Post subject: RE:Multi Threading, safe code? |
|
|
Thank you demonwasp, and thanks for the help with the threading, that really confused me. |
|
|
|
|
|
|
|