package com.correx.testing.contracts.utils

import java.util.concurrent.*

object ConcurrencyRunner {

    fun run(
        threads: Int,
        iterations: Int,
        block: (threadIndex: Int, iteration: Int) -> Unit
    ) {
        val executor = Executors.newFixedThreadPool(threads)

        val start = CountDownLatch(1)
        val done = CountDownLatch(threads)

        repeat(threads) { t ->
            executor.submit {
                start.await()

                try {
                    repeat(iterations) { i ->
                        block(t, i)
                    }
                } finally {
                    done.countDown()
                }
            }
        }

        start.countDown()
        done.await()
        executor.shutdown()
    }
}
