2013-11-26 6 views
2

포크/조인 계산의 예제가 있습니다. 누군가 여기서 제게 어떻게 작동하는지 빨리 설명해 주시겠습니까?포크/조인 계산

def quicksortForkJoin(numbers) { 
    withPool { 
     runForkJoin(0, numbers) {index, list -> 
      def groups = list.groupBy {it <=> list[list.size().intdiv(2)]} 
      if ((list.size() < 2) || (groups.size() == 1)) { 
       return [index: index, list: list.clone()] 
      } 
      (-1..1).each { forkOffChild(it, groups[it] ?: [])} 
      return [index: index, list: childrenResults.sort {it.index}.sum {it.list}] 
     }.list 
    } 
} 

답변

3

def quicksortForkJoin(numbers) { 

    // Create a pool of workers the default size 
    withPool { 

     // Run a fork with index 0 and the numbers 
     runForkJoin(0, numbers) {index, list ->   // [1] 

      // Split numbers into 3 groups: 
      // -1: those less than the "middle" number 
      //  0: those equal to the "middle" number 
      //  1: those greater than the "middle" number 
      def groups = list.groupBy {it <=> list[list.size().intdiv(2)]} 

      // If there are less than 2 numbers to sort, or all numbers are equal 
      if ((list.size() < 2) || (groups.size() == 1)) { 

       // return the index and a clone of the current list 
       return [index: index, list: list.clone()] 
      } 

      // Otherwise, fork off a child process for each of the 
      // groups above (less than, equal and greater than) 
      // forkOffChild will not block, and will effectively go back 
      // to line [1] with the new index and list 
      (-1..1).each { forkOffChild(it, groups[it] ?: [])} 

      // Block waiting for all 3 children to finish, then sort the 
      // results so the indexes are [ -1, 0, 1 ] and then join the 
      // lists of numbers back together 
      return [ index: index, 
        list: childrenResults.sort {it.index}.sum {it.list}] 

      // when done, return the `list` property from the final map 
     }.list 
    } 
} 
+0

대단히 감사합니다. 그러나 나는 여전히 '그룹'으로 그 부분을 이해하지 못한다 : 그것은 어떻게 3 개의 그룹으로 나뉘어 지는가? 이 줄'{it <=> list [list.size(). intdiv (2)]}'는 꽤 혼란 스럽습니다. – user1170330

+1

@ user1170330'list [list.size(). intdiv (2)]'는 중간 요소를 얻습니다 : 즉,'[3, 6, 4, 3, 1]''4 ' . 그래서 이것을 '중반'이라고 부르 자. 그룹 종결은'{it <=> mid}'가됩니다. 우주선 운영자는 기본적으로 두 요소를 '비교'하고 '-1', '0'또는 '1'을 반환합니다. 그래서'groupBy'는리스트에있는 모든 원소를 취하고 so (3), (1), (3), (1), 1 : [6]]' –