Skip to content

Multiprocess Execution

Batman wondered about the behavour of variables in a Robyn multiprocessing environment.

Robyn reassured that it can indeed support them! i.e, handlers can be dispatched to multiple threads.

Any variable used in a multiprocessing environment is shared across multiple processes.

Whilst using multithreading in Robyn, the variables are not protected from multiple threads access by default.

If one needs a variable to be protected within a process, while accessing it from different threads, one can use multiprocessing.Value for achieving the required protection.

py
# GET /hello_world
import threading
import time
from multiprocessing import Value

from robyn import Robyn, Request

app = Robyn(__file__)

count = Value("i", 0)

def counter():
    while True:
        count.value += 1
        time.sleep(0.2)
        print(count.value, "added 1")

@app.get("/")
def index(request):
    return f"{count.value}"

threading.Thread(target=counter, daemon=True).start()

app.start()
py
# GET /hello_world
import threading
import time
from multiprocessing import Value

from robyn import Robyn, Request

app = Robyn(__file__)

count: Value = Value("i", 0)

def counter():
    while True:
        count.value += 1
        time.sleep(0.2)
        print(count.value, "added 1")

@app.get("/")
def index(request: Request):
    return f"{count.value}"

threading.Thread(target=counter, daemon=True).start()

app.start()

What's next?

Batman wondered if it was possible to use Rust directly from Robyn's codebase.

Robyn showed him the path.

Released under the MIT License.