I have a shared piece of code in a function, that should be accessed one at a time . I used mutex.lock/unlock to achieve this while working with coroutines.
public class TestAbc {
val mutex = Mutex()
suspend fun testfunction() {
mutex.lock()
arrayList.add("abc")
hashmap.put("abc", "efg")
mutex.unlock()
}
}
public class InitiatorClass{
val testAbc: TestAbc = TestAbc()
public fun startJob() {
GlobalScope.launch {
testAbc.testfunction()
}
}
}
I tested this by calling Start Job Function twice from a java class ,from different threads.
wanted only one coroutine to access these two dataStructures at once, with help of mutex but its not working.I see multiple coroutines entering the lock.