Thread series 02, multiple threads simultaneously process a time-consuming task to save time, 02 save time

Source: Internet
Author: User

Thread series 02, multiple threads simultaneously process a time-consuming task to save time, 02 save time

When facing a time-consuming task, we can split the task into multiple parts and hand it over to multiple threads for processing at the same time.

 

□A time-consuming Method for counting byte Arrays

The following is used to calculate the size of a byte array.

    class Program
    {
        static byte[] values = new byte[500000000];
        static void Main(string[] args)
        {
            GenerateByteArray();
Console. WriteLine ("calculating the number of bytes ");
            Stopwatch watch = new Stopwatch();
            watch.Start();
            long total = 0;
            for (int i = 0; i < values.Length; i++)
            {
                total += values[i];
            }
            watch.Stop();
Console. WriteLine ("statistical result:" + total );
Console. WriteLine ("computing time:" + watch. Elapsed );
        }
        static void GenerateByteArray()
        {
            var r = new Random(987);
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = (byte)r.Next(10);
            }
        }
    }

If we hand over the statistical work to multiple threads at the same time, can we save the statistical time?

 

□Use multiple threads at the same time

Now we want to divide and divide the task "count byte array size. The first problem is: what criteria are evenly allocated?
-- This is entirely based on personal preferences. Two threads and three threads can be processed. Here, the number of CPUs is evenly allocated, because the number of CPUs can be obtained through Environment. ProcessorCount.

 

The second problem is: what is the average score?
-- For example, there are 4 CPUs
-- The task can be divided into four threads for simultaneous processing.
-- Divide the length of the byte array equally. For example, if the length of the byte array is 1000, the length of each byte array is divided into 4 segments, and the length of each segment is 250.
-- Divide the size of the byte array into four and put them in an array, that is, [sum1, sum2, sum3, sum4]. All elements add up to the total size of the byte array.

    class Program
    {
        static byte[] values = new byte[500000000];
// Put the size of the segmentation statistics in this array, for example, dividing it into 4 equal portions, [,]
        private static long[] partialSum; 
// Divide the length of the values array equally, for example, the length of 1000 is divided into 4 powders, and the partialSize is 250.
        private static int partialSize;
        static void Main(string[] args)
        {
// Determine the array length based on the number of CPUs
            partialSum = new long[Environment.ProcessorCount];
// Determine the equal length of the array based on the number of CPUs
            partialSize = values.Length/Environment.ProcessorCount;
            GenerateByteArray();
Console. WriteLine ("calculating the number of bytes ");
            Stopwatch watch = new Stopwatch();
            watch.Start();
            long total = 0;
            for (int i = 0; i < values.Length; i++)
            {
                total += values[i];
            }
            watch.Stop();
Console. WriteLine ("statistical result:" + total );
Console. WriteLine ("computing time:" + watch. Elapsed );
            Console.WriteLine();
            watch.Reset();
            watch.Start();
            Thread[] threads = new Thread[Environment.ProcessorCount];
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                threads[i] = new Thread(SumPartial);
                threads[i].Start(i);
            }
// Ensure that one thread ends before executing the next thread
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                threads[i].Join();
            }
// Total statistics
            long total2 = 0;
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                total2 += partialSum[i];
            }
            watch.Stop();
Console. WriteLine ("the size of statistics using multipart threads:" + total2 );
Console. WriteLine ("computing time:" + watch. Elapsed );
        }
        /// <summary>
/// Calculate the size of the byte array in Segments
        /// </summary>
/// <Param name = "partialNumber"> for example, if four CPUs exist, the possible values of partialNumber are 0, 1, 2, and 3. </param>
        static void SumPartial(object partialNumber)
        {
            long sum = 0;
            int partialNumberAsInt = (int)partialNumber;
            int baseIndex = partialNumberAsInt * partialSize;
            for (int i = baseIndex; i < baseIndex + partialSize; i++)
            {
                sum += values[i];
            }
            partialSum[partialNumberAsInt] = sum;
        }
        /// <summary>
/// Create a byte array
        /// </summary>
        static void GenerateByteArray()
        {
            var r = new Random(987);
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = (byte)r.Next(10);
            }
        }
    }

Above, the method of calculating the size of the byte array is not the most important, and the thread part is the focus:
○ There are several CPUs, just several threads
○ The thread instance method Start can pass object-type parameters
○ Thread instance method Join, used to ensure that the last thread is executed before the next thread is executed


Here, using multiple threads to process a task at the same time improves the efficiency by about 2.6 times!

 

Summary:
○ A time-consuming task can be handed over to multiple threads for processing at the same time
○ The instance method Join of the thread ensures that the last thread is executed before the next thread is executed.

 

 

The thread series includes:

Thread series 01, front-end thread, back-end thread, thread synchronization thread series 02, multiple threads simultaneously process a time-consuming task to save time thread series 03, multi-thread shared data, multi-thread data sharing
Multiple Threads call the same thread function

Is the thread function you mentioned a general function, a function that generates a thread, or a thread used to run a specific function?

If you want to run the same task with multiple threads in VC, and there is no communication problem or Memory Sharing Problem between these tasks, you can use the following template:
Dword winapi TaskThreadProc (LPVOID)
{
// Independent task
//...
}

Void RunTaskUseMultiThread (int nThreadCount) // The number of threads is nThreadCount
{
HANDLE * threads = new HANDLE [nThreadCount]; // thread HANDLE, used to control the thread status
DWORD * idThreads = new DWORD [nThreadCount]; // thread id, used to send messages to a thread
Int I;
For (I = 0; I <nThreadCount; I ++)
{
Threads [I] = CreateThread (NULL, 0, TaskThreadProc, NULL, create_suincluded, & idThreads [I]); // create a thread
}
For (I = 0; I <nThreadCount; I ++) // as the create_suincluded thread is generated, the thread starts to run.
ResumeThread (threads [I]);
WaitForMultipleObjects (nThreadCount, threads, TRUE, INFINITE); // wait until the thread stops running
For (I = 0; I <nThreadCount; I ++)
CloseHandle (threads [j]); // destroys a thread
Delete [] threads;
Delete [] idThreads;
}

A time-consuming cycle is divided into two cycles into different threads, so that thread synchronization can not improve efficiency

First of all, it is clear that single-core CPU and multi-thread operations are actually applied by each thread for a period of time, but the time is too short. It seems that they are executed at the same time and time-consuming operations, generally, a new thread operation is added to the wait interface, and the callback is completed. The efficiency problem is solved by hardware and an optimization algorithm.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.