Skip to content

Commit

Permalink
Merge pull request #5045 from prakanth97/fork
Browse files Browse the repository at this point in the history
Add bbe for fork statement
  • Loading branch information
prakanth97 authored Apr 17, 2024
2 parents d1b31f5 + e358f31 commit 7761639
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 0 deletions.
22 changes: 22 additions & 0 deletions examples/fork/fork.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import ballerina/io;

public function main(int? userInput) {
if userInput is int {
int num = userInput;
fork {
worker A {
num -> B;
string value = <- B;
io:println(string `Received string '${value}' from worker B`);
}

worker B {
int value = <- A;
io:println(string `Received int '${value}' from worker A`);
"a" -> A;
}
}
} else {
io:println("Not forked");
}
}
7 changes: 7 additions & 0 deletions examples/fork/fork.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Fork

The fork statement starts one or more named workers, which run in parallel with each other, each in its own new strand. Variables and parameters in the scope of the fork statement remain within the scope of the workers. Message passing can be done only between the workers created within the fork statement and cannot be done with the function's default worker and its named workers. Unlike named workers outside a `fork` statement, with a `fork` statement, workers can be defined anywhere within the function body (e.g., within a conditional block).

::: code fork.bal :::

::: out fork.out :::
2 changes: 2 additions & 0 deletions examples/fork/fork.metatags
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
description: This BBE demonstrates how the `fork` statement can be used for concurrency.
keywords: ballerina, ballerina by example, bbe, fork, concurrency, named workers
3 changes: 3 additions & 0 deletions examples/fork/fork.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
$ bal run fork.bal -- 5
Received int '5' from worker A
Received string 'a' from worker B
7 changes: 7 additions & 0 deletions examples/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -1495,6 +1495,13 @@
"verifyBuild": true,
"verifyOutput": true,
"isLearnByExample": true
},
{
"name": "Fork",
"url": "fork",
"verifyBuild": true,
"verifyOutput": false,
"isLearnByExample": true
}
]
},
Expand Down

0 comments on commit 7761639

Please sign in to comment.