Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting normal Threads

Let's say that what I want to do is to validate one million strings, and each validation takes a couple of seconds.

My approach:

I have an array of threads declared like this:

Thread[] workers = new Thread[50];

I don't have all strings in an array, they are got through some calculations, then I don't have all of them when I start the process, but I have a method that returns the next one:

public string next()
{
  //my code
}

I've been able to run all the 50 threads like this:

for (int x = 0; x < 50; x++)
{
workers[x] = new Thread(new ParameterizedThreadStart(myMethod));
workers[x].Start(next());
}

Which swiftly starts all 50 threads "at the same time" and then my log (fed by myMethod) gets 50 responses almost at the same time (1~1.5 second)

How do I get every thread that has just completed to run again with the next string taking into account that the Thread class doesn't expose any event or anything similar ?

Note: I have done some performance tests, and I prefer to use the regular Threads rather than BackgroundWorkers.

Using C# in .net 3.5.

like image 515
Marcelo Avatar asked Jul 30 '26 22:07

Marcelo


2 Answers

This sounds like you should be using the ThreadPool. You could then just do:

while(MoreWorkIsAvailable)
{
    string nextString = next();
    ThreadPool.QueueUserWorkItem(new WaitCallback(myMethod), nextString);
}

The thread pool would even allow you to put a hard cap on the max number of threads to allow to run at a single time via SetMaxThreads.

like image 105
Reed Copsey Avatar answered Aug 01 '26 13:08

Reed Copsey


You can not get an event by the threading system. You can wait for a single thread with Thread.Join, but you can not wait for any thread and get the thread that first completes. Your best approach is to put a while-loop in each thread that polls a queue of work items until the queue is empty.

like image 44
Albin Sunnanbo Avatar answered Aug 01 '26 13:08

Albin Sunnanbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!