Swan Lake Beta3 is here.
import ballerina/io;

int n = 0;

function inc() {
    // Locks the global variable `n` and increments it by 1.
    lock {
        n += 1;
    }

    io:println(n);
}

public function main() {
    inc();
}

Lock Statement

The lock statement allows mutable state to be safely accessed from multiple strands that are running on separate threads. Semantics are like an atomic section: execution of outermost lock block is not interleaved. Naive implementation uses single, global, recursive lock. Efficient implementation can do compile-time lock inference.

import ballerina/io;
int n = 0;
function inc() {
    lock {
        n += 1;
    }

Locks the global variable n and increments it by 1.

    io:println(n);
}
public function main() {
    inc();
}
bal run lock_statement.bal
1
import ballerina/io;

int n = 0;

function inc() {
    // Locks the global variable `n` and increments it by 1.
    lock {
        n += 1;
    }

    io:println(n);
}

public function main() {
    inc();
}

Lock Statement

The lock statement allows mutable state to be safely accessed from multiple strands that are running on separate threads. Semantics are like an atomic section: execution of outermost lock block is not interleaved. Naive implementation uses single, global, recursive lock. Efficient implementation can do compile-time lock inference.

import ballerina/io;
int n = 0;
function inc() {
    lock {
        n += 1;
    }

Locks the global variable n and increments it by 1.

    io:println(n);
}
public function main() {
    inc();
}
bal run lock_statement.bal
1
Subscribe to the newsletter

In the creation of Ballerina, we were inspired by so many technologies. Thank you to all that have come before us (and forgive us if we missed one): Java, Go, C, C++, D, Rust, Haskell, Kotlin, Dart, TypeScript, JavaScript, Python, Perl, Flow, Swift, Elm, RelaxNG, NPM, Crates, Maven, Gradle, Kubernetes, Docker, Envoy, Markdown, GitHub and WSO2.

Cookie Policy

This website uses cookies so that we can provide you with the best user experience. Read our Cookie Policy to find out more.

If you wish to disable cookies you can do so from your browser.

I Understand