2

So we have a task to sort an array using semaphores in Java. The task is pretty easy and I've solved it in nearly couple of minutes but for the last part- merging.

Our task was to divide the given array into two, sort the parts simultaneously (using semaphores) and then merge again (using semaphores).

My question is, what is the purpose of merging it using more than one Thread as while filling the final array each of them have to constantly wait for each other, since only one can push elements to the array at one time?

Or am I missing something? Thanks.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Atais
  • 10,857
  • 6
  • 71
  • 111
  • 1
    Maybe you're just supposed to use a semaphore to wake up a unique merging thread once the sorting threads have finished their work. – JB Nizet Oct 08 '12 at 19:43
  • The two (or more threads) can work simultaneously, you may have to wait for the slowest one, but its faster then doing all the stuff sequentially. – tuergeist Oct 08 '12 at 19:59
  • 2
    @tuergeist Please note that [the homework tag is being phased out and must no longer be used](http://meta.stackexchange.com/q/147100). – Gilles 'SO- stop being evil' Oct 08 '12 at 20:34

1 Answers1

1

You can merge with two different threads from opposite sides of the resulting array. Each thread should fill up to a half of the resulting array. then threads can use semaphores as 'barrier' Implementing an N process barrier using semaphores to wait each other.

Community
  • 1
  • 1
octo
  • 665
  • 3
  • 8
  • Well as much as it is a correct answer, because it works, I find it completely pointless to solve it in that way as 'regular' approach gives comparable effects. – Atais Oct 08 '12 at 20:37