Skip to content
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

Make FastRandom global instance thread-safe #1968

Merged
merged 1 commit into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

package korlibs.datastructure.random

import kotlin.native.concurrent.ThreadLocal
import kotlin.random.Random

@ThreadLocal
private val LocalFastRandom = FastRandom(Random.Default.nextLong())
import korlibs.datastructure.lock.*
import kotlin.random.*

// Copy of XorWowRandom from the Kotlin Standard library but optimizing some methods
open class FastRandom private constructor(
Expand All @@ -18,8 +15,10 @@ open class FastRandom private constructor(
private var addend: Int
) : Random() {
companion object : FastRandom() {
val Default get() = LocalFastRandom
override fun nextBits(bitCount: Int): Int = LocalFastRandom.nextBits(bitCount)
private val _instance = FastRandom(Random.Default.nextLong())
val Default: FastRandom get() = this
private val lock = Lock()
override fun nextBits(bitCount: Int): Int = lock { _instance.nextBits(bitCount) }
}

private constructor(seed1: Int, seed2: Int) :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,10 @@ class FastRandomTest {
assertEquals(3f, floatArrayOf(3f).random(random))
assertEquals(7.0, doubleArrayOf(7.0).random(random))
}

@Test
fun testGlobalInstance() {
println((0 until 10).map { FastRandom.nextInt() })
assertTrue { (0 until 10).map { FastRandom.nextInt() }.distinct().size >= 2 }
}
}