Difference between scala parallel and non-parallel class in parallelsim

In Scala - a functional programming course on coursera, the following code fragment is described in the parallel case. The fragment will succeed if it mutable.Setis replaced by a parallel class.

def intersection(a: GenSet[Int], b: GenSet[Int]): Set[Int] = {
val result = mutable.Set[Int]()
for (x <- a) if (b contains x) result += x
result
}
intersection((0 until 1000).toSet, (0 until 1000 by 4).toSet)
intersection((0 until 1000).par.toSet, (0 until 1000 by 4).par.toSet)

Rule: Avoid mutations in the same memory locations without proper synchronization.

What is the difference between a parallel and non-competitive class, or the reason that a non-competitive class can fail under parallelism?

+4
source share
2 answers

. res2 .

:

for (x <- a) if (b contains x) result += x
result
}

result += x . result.addEntry(x), ,

var h = index(newEntry.hashCode)
var curEntry = table(h)
while (null != curEntry) {
  if (curEntry == newEntry) return false
  h = (h + 1) % table.length
  curEntry = table(h)
  //Statistics.collisions += 1
}
table(h) = newEntry

HashTable. . , newEntry Set, , table(h) = newEntry, hashcode newEntry, newEntry table(h) = newEntry, newEntry .

, , :

for (x <- a) {
  if (b contains x) {
    this.synchronized {
      result += x
    }
  }
}
+2

, . , . .

, , result, / for.

def intersection(a: GenSet[Int], b: GenSet[Int]): Set[Int] = {
val result = mutable.Set[Int]() //This field is not thread safe.
    for (x <- a) if (b contains x) result += x      //mutation occured here.
    result
}

, : intersection((0 until 1000).toSet, (0 until 1000 by 4).toSet). Set 0 to 1000. , for loop, , . x 0 till 1000. , .

intersection((0 until 1000).par.toSet, (0 until 1000 by 4).par.toSet). , , Parallel set. , for loop, / . , < , , , , . , , , .

, concurrency:

" ".

+1

Source: https://habr.com/ru/post/1683725/


All Articles