简体   繁体   中英

C# multithreading Strange behaviour

Basically I'm working on this beat detection algorithm, the strange thing i am encountering right now is that when i split the work load on to another thread. So now i have one main thread and another worker thread. My worker thread somehow is always working faster than the main thread. It seems strange because what i have learned is that the main thread should theoretically always be faster because it is not taking time to initialise the thread. However what i get is even i pass a extra 1024 samples to the worker thread( they are both working with around 30 million samples currently) it is still faster than the main thread. Is it because i have applications running on my main thread? I'm really confused right now. here is the code

UnityEngine.Debug.Log ("T800 Start");
        Step3 s1= new Step3();
        Step3WOMT s2= new Step3WOMT();
        System.Object tempObj= samples2 as System.Object;
        float[] tempArray = new float[eS.Length/ 2];
        System.Threading.ParameterizedThreadStart parameterizedts = new System.Threading.ParameterizedThreadStart(s1.DoStep3);
        System.Threading.Thread T1 = new System.Threading.Thread(parameterizedts);
        T1.Start (tempObj);
        s2.DoStep3(samples1);
        UnityEngine.Debug.Log ("s2");
        //UnityEngine.Debug.Log (stopwatch.ElapsedMilliseconds);
        T1.Join();

Don't worry I'm only using c# features in the multithread so I believe it should be fine. What i am really confused about is that if i comment out the T1.join(); line the whole thing somehow go even slower. Im genuinely confused right now as there seems no reasonable answer to this question.

T1.join() does all the magic. It allow main thread to wait till all the worker threads are complete. Is that necessary ? depends on ur application. it is expected for a main thread to wait for the end of execution of its worker threads.

  1. Your system must have multiple cores.
  2. It's possible that Thread.Start can return not immediately after the thread is initialized. Anyway you should use ThreadPool.EnqueueUserWorkItem and ManualResetEvent to wait instead of join.
  3. To see real results your samples count must be big enough so that thread initialization time is minimal compared to the execution time of your code. ThreadPool often doesn't have to initialize a new thread but it still takes some time to launch your code. I think you should not use multithreading for tasks which takes <~50ms.
  4. If you compare the execution time for big samples count (takes few seconds) you'll see that there is no difference in the performance of the main thread and the background one (unless the main thread have higher priority).

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