Cooperative Multithreading

Multithreading is the capacity to execute simultaneously multiple executions independently from each other. This feature is essential in distributed systems for many reasons. For example, threads can be used to service different clients requesting the same service independently, so they do not interfere with each other. In this section, we present the multithreading support of OiL and how it is used.

Coroutines

Lua does not provide standard support for multithreading. However, it provides the concept of coroutines, which can be used to implement a cooperative multithreading infrastructure. Unlike preemptive multithreading, as provided by Java or POSIX Threads, the execution switch between threads does not occur automatically. Instead the code executed by the coroutine must explicitly signal for execution switch by operation coroutine.yield (···). For further information about Lua coroutines, see Coroutine Manipulation.

Scheduler

Coroutines provide means to create independent execution threads, however it is up to the application to manage the execution of these threads. To perform this management, OiL uses a coroutine scheduler. The scheduler keeps a collection of all the threads of the system. These threads are then scheduled for execution, in such way that whenever a coroutine yields its execution, the scheduler chooses another coroutine for execution following a round-robin algorithm.

Since the coroutine scheduler is not part of the standard virtual machine of Lua, it must be created and started by the application. This can be done by operation oil.main that creates and initiates the execution of the scheduler with a single thread registered that executes the function mainbody provided as parameter. After this operations is called, other threads can be created with operation oil.newthread that creates new coroutines to execute a function.

Limitations

Since the thread scheduler is not integrated to the underlying operating system, any blocking system call performed by a thread will eventually suspend the execution of the application as a whole since the coroutine does not yield the execution back to the scheduler. This is particularly true for file operations that suspend the entire execution of the application regardless of the number of other independent threads that might be ready to execute.

Copyright (C) 2004-2014 Tecgraf, PUC-Rio

This project is currently being maintained by Tecgraf at PUC-Rio.