简体   繁体   中英

The best way to run 200 threads in C#

Previously, I used the following code:

for (int i = 0; i < config.threads; i++)
{
  Thread thread = new Thread(workThread);
  thread.IsBackground = true;
  thread.Start();
}

public static void workThread()
{
    while (true)
    {
        // work, 10 second
    }
}

It works fine, but after 10-15 cycles, begins to work less. Then I wrote a class for the creation of the separate threads:

class ThreadsPool
{
    private static int maxThreads = 0;
    private static Thread[] threadsArray;
    private static int activeThread = 0;


    public static void Initializer(int maxThreads)
    {
        ThreadsPool.maxThreads = maxThreads;
        for (int i = 0; i < maxThreads; i++)
        {
            Thread thread = new Thread(Program.workThread);
            thread.IsBackground = true;
            thread.Start();
        }
        Thread threadDaemon = new Thread(Daemon);
        threadDaemon.IsBackground = true;
        threadDaemon.Start();
    }

    public static void activeThreadMinus()
    {
        Interlocked.Decrement(ref activeThread);
    }

    private static void Daemon()
    {
        while(true)
        {
            if(activeThread < maxThreads)
            {
                Thread thread = new Thread(Program.workThread);
                thread.IsBackground = true;
                thread.Start();
            }
            Thread.Sleep(5);
        }
    }

public static void workThread()
       {
            while (true)
            {
                // work 10 sec
                ThreadsPool.activeThreadMinus();
            }
        }
}

But the problem is that this class creates a memory leak. Do you realize I have to do the work of 10 seconds, an almost infinite number of times, sometimes the number of running threads changes. How this can be done without memory leaks, and without losing performance.

Generate a queue and have as many threads as number of processors. Then make the threads read from the queue and process the messages. Don't destroy the threads, let them run indefinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM