Im trying to count to 200000 in four threads, I want to count with the first both threads to 200_000 and subtract after counting of the both first. I know I can do it with join, but when im starting join it doesn't count because of the add function (counter++)
It look like this:
val s = Semaphore(1)
var count = 0
thread{
repeat(100_000){
s.acquire()
add()
s.release()
println("${Thread.currentThread().name} :$count")
}
}
thread{
repeat(100_000){
s.acquire()
subtract()
s.release()
println("${Thread.currentThread().name} :$count")
}
}
fun add(){
count++
}
fun subtract(){
count--
}
The functions do only add/subtract for the counter variable above the Threads