Mutex for parallel Tasks

Hello Guys,

I’ve task of the same name in different project. when I try to run my build using --parallel, those task run in parallel, but because they access a common resource (a lib file), the build fails.

I would like to implement mutex for that resource. And lock it and unlock it when using it through those tasks.

I did this :


task buildNativeRelease(type: Exec, description: ‘Compile JNI source via ndk-build’) {
while(1){
if(rootProject.ext.mutexNative==“true”){
rootProject.ext.mutexNative = "false"
THE NATIVE TASK
rootProject.ext.mutexNative = "true"
break;
}
}
}


And similar in other one.

When I run in parallel. In the configuration phase they are getting called in parallel using mutex. But when they actually run it, they don’t use mutex.

Any pointers about why this is happening ?

Thanks in advance.

Hey, you can try something like this:

import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock

def lock = new ReentrantLock()
def available = lock.newCondition()
def busy = new AtomicBoolean()
def serializedTasks = []

allprojects {
    tasks.matching { it.name == "buildNativeRelease" }.all {
        serializedTasks << it
        doFirst {
            lock.lock()
            while (busy.get()) {
                available.await()
            }
            busy.set(true)
        }
    }
}
gradle.taskGraph.afterTask {
    if (it in serializedTasks && lock.heldByCurrentThread) {
        busy.set(false)
        available.signal()
        lock.unlock()
    }
}
2 Likes