3

I try to find the duplicated element in an array(sorted) using threads. My idea is to split the array in two and assign each half to a thread. But when i run the code I get the ~exact same time like i didn't used threads.

My code:

        Parallel.Invoke(()=>Search(0,elements.Length/2,elements),
            ()=>Search(elements.Length/2,elements.Length-1,elements));

And Search method:

    public static void Search(int start , int stop , int[] elements)
    {
        for (var i = start; i < stop; i++)
        {
            if (elements[i] == elements[i + 1])
            {
                Console.WriteLine("found ,time  " + (DateTime.Now - _start));
                break;
            }
        }
    }

Array is 100000000 elements. Also i am not looking for the LINQ -like solution.

15
  • solution in this might help you stackoverflow.com/questions/19757992/…
    – omi
    Mar 9, 2017 at 12:59
  • How big is the array you used to test this? The TPL decides very smart if a new thread is necessary or if the overhead to create/take a thread and switch contexts would eat up any benefit. So I guess Parallel.Invoke simply uses only one thread for your search.
    – René Vogt
    Mar 9, 2017 at 13:00
  • 3
    Multithreading should be done only for "big" things (it is slow to setup) I'll say that anything that doesn't impact the user interface and that is shorter than 0.1 sec shouldn't be multithreaded. And between 0.1 and 1 sec I would think quite much before doing it.
    – xanatos
    Mar 9, 2017 at 13:03
  • 3
    yeah but how will each thread know about dupes in the other chunks?
    – Botonomous
    Mar 9, 2017 at 13:03
  • 2
    This approach suffers from a fundamental problem: if you're going to divide and conquer, you must make sure you don't accidentally split the input on exactly a value that's duplicated, otherwise neither half will actually contain a duplicate. So at the very least, a custom partitioning function is needed that checks this before partitioning. On the whole, this seems vastly more trouble than it's worth. How did the array get sorted/constructed? Is there any way that algorithm could be adapted to detect the duplicates as it works? Mar 9, 2017 at 13:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.