How to use this semaphore

List<int> cuis = PersistencyServices.GetListOfAllCui(); ResourceLock = new Semaphore(3, 5); foreach (var cui in cuis) { Thread workThread = new Thread(new ParameterizedThreadStart(Worker)); workThread.Start(cui); } } public static void Worker(object cui) { ResourceLock.WaitOne(); Debug.WriteLine(String.Format("Thread for cui {0} in", cui)); Thread.Sleep(5000); ResourceLock.Release(); } 

This code allows only 3 threads to be in the critical area at a time. But the problem is that, since the list contains more than 1 million records, I get an OutOfMemoryException. I think this is due to the fact that even if the semaphore allows only 3 threads to enter the critical region, but 1 million threads are created that wait for the semaphore. How can I change the code to prevent this? Please, help

+4
source share
1 answer

You really don't want a million threads. It's not clear what you are doing, but it seems that Parallel.ForEach(...) will do everything you need with a little work and a lot of sanity.

If you want to use only 3 threads:

 Parallel.ForEach(cuis, new ParallelOptions { MaxDegreeOfParallelism = 3 }, Worker); 

with:

 public static void Worker(int cui) { Debug.WriteLine(String.Format("Thread for cui {0} in", cui)); Thread.Sleep(5000); } 

If you really want to use a semaphore, use WaitOne in a loop:

 foreach (var cui in cuis) { ResourceLock.WaitOne(); Thread workThread = new Thread(new ParameterizedThreadStart(Worker)); workThread.Start(cui); } ... public static void Worker(object cui) { Debug.WriteLine(String.Format("Thread for cui {0} in", cui)); Thread.Sleep(5000); ResourceLock.Release(); } 
+3
source

Source: https://habr.com/ru/post/1340430/


All Articles