X
X
Xveeder2018-07-13 19:18:28
C++ / C#
Xveeder, 2018-07-13 19:18:28

How to limit the number of threads running at the same time?

Good day, comrades.
Got a question. For example, I have 100 defined entities that perform certain actions. I want to run them in a multithread, but so that no more than 15 threads work at the same time, and at the time when a certain entity left the thread (i.e. completed its task), a new one immediately entered this thread.
How to do it (when working with thread)? At first glance, the simplest method is the semaphore. But is it right?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
basrach, 2018-07-14
@Xveeder

The easiest option is to use Parallel.Foreach .

var myEntities = new MyEntity[100];
var maxThreads = 15;

System.Threading.Tasks.Parallel.ForEach(
    myEntities,
    new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = maxThreads },
    entity =>
    {
        entity.Do()
    });

The second option is to use Semaphore or SemaphoreSlim .
var myEntities = new MyEntity[100];
var maxThreads = 15;	

var semaphoreSlim = new SemaphoreSlim(maxThreads);
var tasks = new List<Task>(myEntities.Length);
foreach (var entity in myEntities)
{
  tasks.Add(Task.Run(() =>
  {
    semaphoreSlim.Wait();
    try
    {
      entity.Do();
    }
    finally
    {
      semaphoreSlim.Release();	
    }
  }));
}

Task.WaitAll(tasks.ToArray());

If you want to use Thread class directly then
var myEntities = new MyEntity[100];
var maxThreads = 3;	

var semaphore = new Semaphore(maxThreads, maxThreads);
var threads = new List<Thread>(myEntities.Length);
foreach (var entity in myEntities)
{
  var thread = new Thread(() =>
  {
    semaphore.WaitOne();
    try
    {
      entity.Do();
    }
    finally
    {
      semaphore.Release();
    }
  });
  
  threads.Add(thread);
  
  thread.Start();
}

foreach (var thread in threads)
  thread.Join();

Although from the conditions of the task it seems that it is quite possible to get by with Task. Task is also preferable for the reason that threads are reused. Those. there will be as many threads involved as there are tasks running at the same time, for example, 15. In the case of creating a thread directly through the Thread class, 15 will work, the rest will just wait, while still wasting resources.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question