Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid race conditions with scala parallel collections

Are parallel collections intended to do operations with side effects? If so, how can you avoid race conditions? For example:

var sum=0
(1 to 10000).foreach(n=>sum+=n); println(sum)

50005000

no problem with this. But if try to parallelize, race conditions happen:

var sum=0
(1 to 10000).par.foreach(n=>sum+=n);println(sum)

49980037
like image 526
Giuliano Avatar asked Mar 30 '12 23:03

Giuliano


People also ask

What are recommended ways to avoid race condition?

To avoid race conditions, any operation on a shared resource – that is, on a resource that can be shared between threads – must be executed atomically. One way to achieve atomicity is by using critical sections — mutually exclusive parts of the program.

How do you avoid race condition in multithreading?

Race conditions can be avoided by proper thread synchronization in critical sections. Thread synchronization can be achieved using a synchronized block of Java code. Thread synchronization can also be achieved using other synchronization constructs like locks or atomic variables like java.

How do you handle race condition in multithreading?

an easy way to fix "check and act" race conditions is to synchronized keyword and enforce locking which will make this operation atomic and guarantees that block or method will only be executed by one thread and result of the operation will be visible to all threads once synchronized blocks completed or thread exited ...

What is race condition in parallel programming?

Definition. A race condition occurs in a parallel program execution when two or more threads access a common resource, e.g., a variable in shared memory, and the order of the accesses depends on the timing, i.e., the progress of individual threads. The disposition for a race condition is in the parallel program.


1 Answers

Quick answer: don't do that. Parallel code should be parallel, not concurrent.

Better answer:

val sum = (1 to 10000).par.reduce(_+_) // depends on commutativity and associativity

See also aggregate.

like image 178
Daniel C. Sobral Avatar answered Sep 27 '22 23:09

Daniel C. Sobral