Skip to content

chap02 ex1 better implement #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions src/main/scala/org/learningconcurrency/exercises/ch2/ex1.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,15 @@ import org.learningconcurrency.ch2.thread
object Ex1 extends App {

def parallel[A, B](a: =>A, b: =>B): (A, B) = {
var aVal: A = null.asInstanceOf[A]
var bVal: B = null.asInstanceOf[B]

val t1 = thread {
aVal = a
log(aVal.toString())
a
}

val t2 = thread {
bVal = b
log(bVal.toString())
b
}

t1.join()
t2.join()

(aVal, bVal)
(a, b)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@amoszhou Commeny from @ryblovAV is correct - the expression a is by name (not lazy), and it will be executed twice now. The first time in parallel in the thread statement, and the second time when returning from the method. This effectively removes parallelism, and if the a or b are side-effecting, will execute the side-effect twice.

If you want nicer code, you could do this:

lazy evaluatedA = a
lazy evaluatedB = b

val t1 = thread {
  evaluatedA
}
...
(evaluatedA, evaluatedB)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, thank you

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are welcome, just don't forget to add lazy vals and push again to sync the pull request if you made any changes.

}

}