Does start the same thread possible?

everybody I have a some computation program. Now, this program is a single-thread, I need to enhance it to do it multi-thread. In general, program computes, dynamic evolution of thermal circuit (Some configured types of different involved elements (Tube, Pump, Active zone, and its connection), for each of it for every time step program calculates diffusion equations ( Problem is, on every time steps each involved element could be handled separately, but on every new time steps all elements should synchronize each other. I've decided to do it by starting on each time step one Thread per element, to solve it.

private void SolveElementDynamic(object element) { if (element is PJunction) { ((PJunction)element).SolveDynamic(); } else if (element is PElementData) { ((PElementData)element).SolveDynamic(); } } public void SolveDynamic() { ParameterizedThreadStart threadStart = new ParameterizedThreadStart(SolveElementDynamic); for (int i = 0; i < _elementDataCollection.Count; i++) { _threadArray.Add(new Thread(threadStart)); } int j = 0; foreach (object element in _elementDataCollection) { ((Thread)_threadArray[j]).Start(element); j++; } }

But it seems that creating new Thread is too expensive in comparison with calculating one element per step. I've tried to create Thread array, only one time at the start of the computation. But unfortunately It is seems that Thread object can't be started more than one times?

// Thread's array created before public void SolveDynamic() { int j = 0; foreach (object element in _elementDataCollection) { ((Thread)_threadArray[j]).Start(element); j++; } }

Is there any way to do it? Or is there any way to do it better?)

PS I've never encountered with Threading in .Net, and I have a small practice in threading programming

-------------Problems Reply------------

try this How to: Use a Thread Pool (C# Programming Guide).

First, why your solution does NOT work:

A .NET thread is associated with an OS object (the os thread) - and a windows (and unix as well for that matter) contains its own execution stack. Now, if you where to have multiple execution units use the same stack, it would result in absolutely unpredictable behaviour. Therefor: One thread object can only ever be running or not running - not something like running 10 times.

Using a thread array is possible - but you need to create a new thread element for each index.

The problem with using a new thread for each step of a computation is that the creation of a thread itself is rather costly - it needs to do a system call, create a stack, a kernel object and so forth.

There are effectively two things you might wish to do:

First, assign a lot more than a single step to each thread. A more effective version of this is to have a central (synchronized) work queue where each thread can get more work. You then only create a single thread per available CPU and still usually assign more than a single step of work at once (otherwise your bottleneck will be the work distribution).

Second, reuse your existing threads. Whether by using the .NET thread pool, or by simply not recreating your threads, does not matter in this context - a synchronization of existing threads is a lot cheaper than complete recreation. Also, if you use slim locks, you can completely avoid the os call.

Why do you need your program to be multithreaded? It's going to make your program much more complex, so what's the benefit you are hoping for? Do you want to utilize more cores to increase speed?

Assuming that you want to utilize more cores, you might want to look at .NET 4 and Parallel Programming.

It's still in Beta right now but it looks pretty stable, and it will likely be released for production soon.

Due to limited experience with paralellism in C#, I would recommend looking into PLINQ and the Task Parallel Library that it is built on. This framework is currently part of a seperate 'add-on' library for .Net 3.0, but will be built in to the .Net 4.0 framework.

You could do what you're currently trying to do using the Task constructs, or the parallel For extension methods:

foreach (var element in var _elementDataCollection)
var task = new Task(element.SolveDynamic);


Parallel.ForEach(_elementDataCollection, x => {

Example Post Using the TPL

Category:c# Views:0 Time:2009-12-13

Related post

  • How do I make event callbacks into my win forms thread safe? 2008-08-08

    When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. T

  • How to wait for thread complete before continuing? 2008-08-09

    I have some code for starting a thread on the .NET CF 2.0: ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); If I call this inside a loop the items complete out of order. How do introduce a wait after t.Start()

  • Thread safe lazy construction of a singleton in C++ 2008-08-09

    Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variabl

  • Is the C# static constructor thread safe? 2008-08-10

    In other words, is this Singleton implementation thread safe: public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return insta

  • Compact Framework/Threading - MessageBox displays over other controls after option is chosen 2008-08-13

    I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process: Clicks button Method checks for updates, count is returned. If greater than 0, then ask the

  • Windows Forms Threading and Events - ListBox updates promptly but progressbar experiences huge delay 2008-08-15

    Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically differen

  • How should I unit test threaded code? 2008-08-15

    Hot-on-the-heels of my previous unit testing related question, here's another toughie: I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I'd like to ask how people have gone ab

  • A ThreadStateException occures when trying to restart a thread 2008-08-16

    From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows: // Make sure the thread is done stopping while (this.mThread.ThreadState == ThreadState.Running) { Thread.Sleep(0

  • Cleanest Way to Invoke Cross-Thread Events 2008-08-22

    I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the c

  • How to abort threads created with ThreadPool.QueueUserWorkItem 2008-08-25

    is there a way to abort threads created with QueueUserWorkItem? Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically? --------------Solutions------------- You don't need to abort t

  • Why stateless session beans are single threaded? 2008-08-27

    As per my understanding stateless session beans are used to code the business logic. They can not store data in their instance variables because their instance is shared by multiple requests. So they seem to be more like Singleton classes. However th

  • Thread not waking up from Thread.Sleep() 2008-08-27

    We have a Windows Service written in C#. The service spawns a thread that does this: private void ThreadWorkerFunction() { while(false == _stop) // stop flag set by other thread { try { openConnection(); doStuff(); closeConnection(); } catch (Excepti

  • JavaScript and Threads 2008-08-27

    Is there some way to do multi-threading in JavaScript? --------------Solutions------------- See for the most up-to-date support info. The following was the state of support circa 2009. The words you want to google fo

  • How do threads work in Python, and what are common Python-threading specific pitfalls? 2008-08-27

    I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject

  • How scalable is System.Threading.Timer? 2008-08-28

    I'm writing an app that will need to make use of Timers, but potentially very many of them. How scalable is the System.Threading.Timer class? The documentation merely say it's "lightweight", but doesn't explain further. Do these timers get sucked int

  • How do you minimize the number of threads used in a tcp server application? 2008-08-28

    I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc. Let's assume for the purposes of this question that the reque

  • How do I spawn threads on different CPU cores? 2008-08-28

    Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3's. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had a

  • Are Python threads buggy? 2008-08-29

    A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? --------------Solutions------------- Python threads are good for concurrent I/

  • C++ Thread question - setting a value to indicate the thread has finished 2008-08-29

    Is the following safe? I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program. Using the boost libraries I have written code something like this: thrd = new boost::thread(boost::bind(&myclass:

  • Task oriented thread pooling 2008-08-31

    I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below:

Copyright (C), All Rights Reserved.

processed in 0.084 (s). 11 q(s)