Reputation: 3891
Is it possible, and is there a code example. On how to make multiple instances of a single thread.
a quick example is just
Thread foo = new Thread(testThread);
foo.Start(); // but start more than once instance
@Andrew Well, when using a web client to download a page it takes about 0.5 seconds. When I make multiple threads that do the same task (copy and pasting the same thread under different function names and running them simultaneously using a global list and indexer for the for loop. With 4 copy threads it gets a page downloaded at about 0.15 seconds.
3 times faster from 4 threads is nice but I want a more clean solution
Upvotes: 0
Views: 1877
Reputation: 11662
The thread instance is not the same as the thread logic. So you can create multiple threads using the same method, you don't have to copy-and-paste the code into separate identical ones:
for( int i=0; i<4; i++ )
(new Thread(threadProc)).Start();
This is legal and may do what you need -- but per the comments, if you do need parallelism then it would be wiser to use the ThreadPool or else use TPL Tasks:
for( int i=0; i<4; i++ )
ThreadPool.QueueUserWorkItem(threadProc);
for( int i=0; i<4; i++ )
(new Task( threadProc )).Start();
These variations can save you the overhead of creating and destroying individual threads and can achieve better overall utilization.
All these approaches have variations where you can pass parameters to your function, for example the variable i
or other information to divide the work. See the docs for details, e.g. http://msdn.microsoft.com/en-us/library/kbf0f1ct.aspx
Upvotes: 3