Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 773
SailingOnThoughts Avatar asked Apr 22 '15 05:04

SailingOnThoughts


1 Answers

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.

like image 92
Sankara Narayanan Avatar answered Sep 23 '22 23:09

Sankara Narayanan