From bba4ecea15320dfbf8edf35f7361de374d895ace Mon Sep 17 00:00:00 2001 From: Benoit Germain Date: Wed, 26 Sep 2012 21:22:30 +0200 Subject: version 3.4.0 * new method linda:dump() that outputs the full contents of a linda as a table, also linked to __towatch for Decoda support * linda:receive() API change! * instead of [val, key], linda:receive( timeout, key) returns [key, val] * instead of [val, [...]], linda:receive( timeout, linda.batched key) returns [key, val[, ...]] this is to unify the return values of regular and batched mode, and to be able to tell when batched mode is interrupted by a lane cancellation * fixed Lua 5.2 build to take into account the "loaders"->"searchers" name change in 'package' module. * a bit of html cleanup and added some infos in the documentation regarding the Lanes internals --- docs/index.html | 1930 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 1052 insertions(+), 878 deletions(-) (limited to 'docs') diff --git a/docs/index.html b/docs/index.html index 932a712..bb64ba2 100644 --- a/docs/index.html +++ b/docs/index.html @@ -5,61 +5,74 @@ - - + + - Lua Lanes - multithreading in Lua + Lua Lanes - multithreading in Lua -
-
- -
- - - - - - - - - -
- - Lua - Lua - Lua - Lua - Lua -

Lua Lanes - multithreading in Lua

-
-

- Description · - Supported systems · - Building and Installing -

- Creation · - Status · - Results and errors -

- Cancelling · - Finalizers · - Lindas · - Timers · - Locks etc. -

- Other issues · - Change log - - -


Copyright © 2007-12 Asko Kauppi, Benoit Germain. All rights reserved. -
Lua Lanes is published under the same MIT license as Lua 5.1 and 5.2. -

This document was revised on 10-Sep-12, and applies to version 3.3.0 -

- -
+
+
+ +
+ + + + + + + +
+ + Lua + Lua + Lua + Lua + Lua + +

Lua Lanes - multithreading in Lua

+ +

+ Description · + Supported systems · + Building and Installing +

+ +

+ Creation · + Status · + Results and errors +

+ +

+ Cancelling · + Finalizers · + Lindas · + Timers · + Locks etc. +

+ +

+ Other issues · + Change log +

+ + + +

+
+ Copyright © 2007-12 Asko Kauppi, Benoit Germain. All rights reserved. +
+ Lua Lanes is published under the same MIT license as Lua 5.1 and 5.2. +

+ +

+ This document was revised on 25-Sep-12, and applies to version 3.4.0. +

+
+
@@ -67,50 +80,40 @@

Description

-

Lua Lanes is a Lua extension library providing - the possibility to run multiple Lua states in parallel. It is intended to - be used for optimizing performance on multicore CPU's and to study ways to make Lua programs naturally parallel to begin with. -

- Lanes is included into your software by the regular - require "lanes" method. No C side programming is needed; all APIs are Lua side, and most existing extension modules should - work seamlessly together with the multiple lanes. -

+

+ Lua Lanes is a Lua extension library providing the possibility to run multiple Lua states in parallel. It is intended to be used for optimizing performance on multicore CPU's and to study ways to make Lua programs naturally parallel to begin with. +

+

+ Lanes is included into your software by the regular require "lanes" method. No C side programming is needed; all APIs are Lua side, and most existing extension modules should work seamlessly together with the multiple lanes. +

+

Starting with version 3.1.6, Lanes should build and run identically with either Lua 5.1 or Lua 5.2. -

+

+

See comparison of Lua Lanes with other Lua multithreading solutions. -

-

Features:

- - - - -

Limitations:

- - +

+

+

Features:

+ + + + +

Limitations:

+ +

@@ -118,23 +121,24 @@

Supported systems

-

Lua Lanes supports the following operating systems: +

+ Lua Lanes supports the following operating systems: -

-

The underlying threading code can be compiled either towards Win32 API - or Pthreads. Unfortunately, thread prioritization under Pthreads is a JOKE, - requiring OS specific tweaks and guessing undocumented behaviour. Other features should be portable to any modern platform. -

+

+

+ The underlying threading code can be compiled either towards Win32 API or Pthreads. Unfortunately, thread prioritization under Pthreads is a JOKE, + requiring OS specific tweaks and guessing undocumented behaviour. Other features should be portable to any modern platform.

@@ -142,258 +146,373 @@

Building and Installing

-

Lua Lanes is built simply by make on the supported platforms -(make-vc for Visual C++). See README for system specific -details and limitations. +

+ Lua Lanes is built simply by make on the supported platforms (make-vc for Visual C++). See README for system specific details and limitations.

-

To install Lanes, all you need are the lanes.lua and lanes/core.so|dll -files to be reachable by Lua (see LUA_PATH, LUA_CPATH). - -Or use Lua Rocks package management. +

+ To install Lanes, all you need are the lanes.lua and lanes/core.so|dll files to be reachable by Lua (see LUA_PATH, LUA_CPATH). + Or use Lua Rocks package management.

-  > luarocks search lanes
-    ... output listing Lua Lanes is there ...
+	> luarocks search lanes
+	... output listing Lua Lanes is there ...
 
-  > luarocks install lanes
-    ... output ...
+	> luarocks install lanes
+	... output ...
 

-

Initialization

- -

- The following sample shows how to initialize the Lanes module. -

- - - -
-
-          local lanes = require "lanes".configure()
-        
-
- -

- Starting with version 3.0-beta, requiring the module follows Lua 5.2 rules: - the module is not available under the global name "lanes", but has to be accessed - through require's return value. - After lanes is required, it is necessary to call lanes.configure(), which is the - only function exposed by the module at this point. Calling configure() will - perform one-time initializations and make the rest of the API available. - At the same time, configure() itself will be replaced by another function that - raises an error if called again with differing arguments. -

- -

- - -
- - lanes.configure( [opt_tbl]) - -
-

-

- lanes.configure accepts an optional options table as sole argument. - - - - - - - - - - - - -
- .nb_keepers
N
- Controls the number of keeper states used internally by lindas to transfer data between lanes. (see below). Default is 1. -
- .with_timers
nil/false/anything
- - If equal to false, Lanes doesn't start the timer service, - and the associated API will be absent from the interface (see below). - Any other value (including nil), starts the timer service. Default is true. -
- - .on_create_state
C function/nil -
- - If provided, will be called in every created Lua state (keepers and lanes) right after it is created, and *before* any library is loaded. - That way, all C functions it loads in the state can be added to the function lookup database. Default is nil. -
- .shutdown_timeout
N
- (Since v3.3.0) Sets the duration in seconds Lanes will wait for graceful termination of running lanes at application shutdown. Irrelevant for builds using pthreads. Default is 0.25. -
-

Creation

+

Initialization

-

The following sample shows preparing a function for parallel calling, and -calling it with varying arguments. Each of the two results is calculated in -a separate OS thread, parallel to the calling one. Reading the results -joins the threads, waiting for any results not already there. +

+ The following sample shows how to initialize the Lanes module.

-
-
-  local lanes = require "lanes"
-  lanes.configure()
+
+	
+		
+	
+
+
	local lanes = require "lanes".configure()
+
- f= lanes.gen( function(n) return 2*n end ) - a= f(1) - b= f(2) +

+ Starting with version 3.0-beta, requiring the module follows Lua 5.2 rules: the module is not available under the global name "lanes", but has to be accessed through require's return value. +

+

+ After lanes is required, it is necessary to call lanes.configure(), which is the only function exposed by the module at this point. Calling configure() will perform one-time initializations and make the rest of the API available. +

+

+ At the same time, configure() itself will be replaced by another function that raises an error if called again with differing arguments. +

- print( a[1], b[1] ) -- 2 4 -
-
+

+ + + + +
+
	lanes.configure( [opt_tbl])
+
+

-
- func= lanes.gen( [libs_str | opt_tbl [, ...],] lane_func ) -

- lane_h= func( ... )
+ lanes.configure accepts an optional options table as sole argument. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
namevaluedefinition
+ .nb_keepers + integer >= 1 + Controls the number of keeper states used internally by lindas to transfer data between lanes. (see below). Default is 1. +
+ .with_timers + + nil/false/anything + + If equal to false, Lanes doesn't start the timer service, and the associated API will be absent from the interface (see below). + Any other non-nil value starts the timer service. Default is true. +
+ .on_create_state + + C function/nil + + If provided, will be called in every created Lua state (keepers and lanes) right after it is created, and *before* any library is loaded. That way, all C functions it loads in the state can be added to the function lookup database. Default is nil. +
+ .shutdown_timeout
+
+ number >= 0 + + (Since v3.3.0) Sets the duration in seconds Lanes will wait for graceful termination of running lanes at application shutdown. Irrelevant for builds using pthreads. Default is 0.25. +
+

+ +
+

Creation

+ +

+ The following sample shows preparing a function for parallel calling, and calling it with varying arguments. Each of the two results is calculated in a separate OS thread, parallel to the calling one. Reading the results joins the threads, waiting for any results not already there. +

+ + + + +
+
	local lanes = require "lanes".configure()
+
+
	f = lanes.gen( function( n) return 2 * n end)
+
	a = f( 1)
+
	b = f( 2)
+
+
	print( a[1], b[1] )     -- 2    4
+
+
+ + + + +
+
	func = lanes.gen( [libs_str | opt_tbl [, ...],] lane_func)
+
	lane_h = func( ...)
+
+ +

+ The function returned by lanes.gen() is a "generator" for launching any number of lanes. They will share code, options, initial globals, but the particular arguments may vary. Only calling the generator function actually launches a lane, and provides a handle for controlling it. +
+ Alternatively, lane_func may be a string, in which case it will be compiled in the lane. This was to be able to launch lanes with older versions of LuaJIT, which didn't not support lua_dump, used internally to transfer functions to the lane.

+

- The function returned by lanes.gen() is a "generator" for - launching any number of lanes. They will share code, options, initial globals, - but the particular arguments may vary. Only calling the generator function - actually launches a lane, and provides a handle for controlling it. - Alternatively, lane_func may be a string, in which case it will be compiled - in the lane. This was to be able to launch lanes with older versions of LuaJIT, - which didn't not support lua_dump, used internally to transfer functions to the lane. - -

-Lanes automatically copies upvalues over to the new lanes, so you -need not wrap all the required elements into one 'wrapper' function. If -lane_func uses some local values, or local functions, they will be there -also in the new lanes. -

- libs_str defines the standard libraries made available to the - new Lua state: - - - - - - - - - - - - -
- -
(nothing)no standard libraries (default)
- "base" or "" - root level names, print, assert, unpack etc.
"coroutine"coroutine.* namespace (part of base in Lua 5.1 and 5.2)
"debug"debug.* namespace
"io"io.* namespace
"math"math.* namespace
"os"os.* namespace
"package"package.* namespace and require
"string"string.* namespace
"table"table.* namespace
"*"all standard libraries (including those specific to LuaJIT and not listed above)
- -

- Initializing the standard libs takes a bit of time at each lane invocation. - This is the main reason why "no libraries" is the default. -

- - opt_tbl is a collection of named options to control the way - lanes are run: -

- - - - - - - - - - - - - - - - -
- .cancelstep
N / true
- By default, lanes are only cancellable when they enter a pending - :receive() or :send() call. - With this option, one can set cancellation check to occur every N - Lua statements. The value true uses a default value (100). - It is also possible to manually test for cancel requests with cancel_test(). -
- .globals
globals_tbl
- - Sets the globals table for the launched threads. This can be used for giving - them constants. The key/value pairs of globals_tbl are transfered in the lane globals after the libraries have been loaded and the modules required. -
- The global values of different lanes are in no manner connected; - modifying one will only affect the particular lane. -
- - .required
modules_tbl -
- - Lists modules that have to be required in order to be able to trasnfer - functions they exposed. Starting with Lanes 3.0-beta, non-Lua functions are - no longer copied by recreating a C closure from a C pointer, but are searched - in lookup tables. These tables are built from the modules listed here. required - must be a list of strings, each one being the name of a module to be required. -
- .priority
-2..+2
- The priority of lanes generated. -2 is lowest, +2 is highest. -
- Implementation and dependability of priorities varies - by platform. Especially Linux kernel 2.6 is not supporting priorities in user mode. -
- - .package
-
- package contents overrides, if needed. - Specifying it when libs_str doesn't cause the package library to be loaded will generate an error. - If not specified, the created lane will receive the current values of package. Only path, cpath, preload and loaders are transfered. -
-
-

Each lane also gets a function set_debug_threadname() that it can use anytime to do as the name says. -Supported debuggers are Microsoft Visual Studio (for the C side) and Decoda (for the Lua side). -

-

+ +

+ libs_str defines the standard libraries made available to the new Lua state: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
(nothing)no standard libraries (default)
+ "base" or "" + + + root level names, print, assert, unpack etc. +
+ + "coroutine" + + + coroutine.* namespace (part of base in Lua 5.1 and 5.2) +
+ + "debug" + + + debug.* namespace +
+ + "io" + + + io.* namespace +
+ + "math" + + + math.* namespace +
+ + "os" + + + os.* namespace +
+ + "package" + + + package.* namespace and require +
+ + "string" + + + string.* namespace +
+ + "table" + + + table.* namespace +
+ + "*" + + + all standard libraries (including those specific to LuaJIT and not listed above) +
+

+ +

+ Initializing the standard libs takes a bit of time at each lane invocation. This is the main reason why "no libraries" is the default. +

+ +

+ opt_tbl is a collection of named options to control the way lanes are run: +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
namevaluedefinition
+ .cancelstep + integer >= 1/true + By default, lanes are only cancellable when they enter a pending :receive() or :send() call. With this option, one can set cancellation check to occur every N Lua statements. The value true uses a default value (100). + It is also possible to manually test for cancel requests with cancel_test(). +
+ .globals + table + Sets the globals table for the launched threads. This can be used for giving them constants. The key/value pairs of table are transfered in the lane globals after the libraries have been loaded and the modules required. +
+ The global values of different lanes are in no manner connected; modifying one will only affect the particular lane. +
+ .required + table + Lists modules that have to be required in order to be able to transfer functions they exposed. Starting with Lanes 3.0-beta, non-Lua functions are no longer copied by recreating a C closure from a C pointer, but are searched in lookup tables. + These tables are built from the modules listed here. required must be a list of strings, each one being the name of a module to be required. Each module is required with require() before the lanes function is invoked. + So, from the required module's point of view, requiring it manually from inside the lane body or having it required this way doesn't change anything. From the lane body's point of view, the only difference is that a module not creating a global won't be accessible. + Therefore, a lane body will also have to require a module manually, but this won't do anything more (see Lua's require documentation). +
+ .priority + integer -2..+2 + The priority of lanes generated. -2 is lowest, +2 is highest. +
+ Implementation and dependability of priorities varies by platform. Especially Linux kernel 2.6 is not supporting priorities in user mode. +
+ .package + table + Specifying it when libs_str doesn't cause the package library to be loaded will generate an error. +
+ If not specified, the created lane will receive the current values of package. Only path, cpath, preload and loaders (Lua 5.1)/searchers (Lua 5.2) are transfered. +
+ +

+ Each lane also gets a function set_debug_threadname() that it can use anytime to do as the name says. Supported debuggers are Microsoft Visual Studio (for the C side) and Decoda (for the Lua side). +

+ +

If a lane body pulls a C function imported by a module required before Lanes itself (thus not through a hooked require), the lane generator creation will raise an error. The function name it shows is a path where it was found by scanning _G. As a utility, the name guessing functionality is exposed as such: - - -
- - "type", "name" = lanes.nameof( o) - -
+ + + + + +
+
	"type", "name" = lanes.nameof( o)
+

Free running lanes

-The lane handles are allowed to be 'let loose'; in other words you may execute -a lane simply by: + The lane handles are allowed to be 'let loose'; in other words you may execute a lane simply by: -

-    lanes.gen( function() ... end ) ()
-
+ + + + +
+
	lanes.gen( function( params) ... end ) ( ...)
+
-Normally, this kind of lanes will be in an eternal loop handling messages. -Since the lane handle is gone, -there is no way to control such a lane from the outside, nor read its potential -return values. Then again, such a lane does not even normally return. + Normally, this kind of lanes will be in an eternal loop handling messages. Since the lane handle is gone, there is no way to control such a lane from the outside, nor read its potential return values. Then again, such a lane does not even normally return.

@@ -401,26 +520,95 @@ return values. Then again, such a lane does not even normally return.

Status

-
- str= lane_h.status -
+ + + + +
+
	str = lane_h.status
+
-

The current execution state of a lane can be read via its status -member, providing one of these values: (2 +

+ The current execution state of a lane can be read via its status member, providing one of these values: (2) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ "pending" + + Not started yet. Shouldn't stay very long in that state. +
+ + + "running" + + + + running, not suspended on a Linda call. +
+ + "waiting" + + + waiting at a Linda :receive() or :send() +
+ + "done" + + + finished executing (results are ready) +
+ + "error" + + + met an error (reading results will propagate it) +
+ + "cancelled" + + + received cancellation and finished itself. +
+ + "killed" + + + was forcefully killed by lane_h:cancel() (since v3.3.0) +
+

- - - - - - - - -
"pending"not started, yet
"running"running
"waiting"waiting at a Linda :receive() or :send()
"done"finished executing (results are ready)
"error"met an error (reading results will propagate it)
"cancelled"received cancellation and finished itself
"killed"was forcefully killed by lane_h:cancel() (since v3.3.0)
-

- This is similar to coroutine.status, which has: "running" / - "suspended" / "normal" / "dead". Not using the - exact same names is intentional. +

+ This is similar to coroutine.status, which has: "running" / "suspended" / "normal" / "dead". Not using the exact same names is intentional.

@@ -428,101 +616,110 @@ member, providing one of these values: (2

Results and errors

-

A lane can be waited upon by simply reading its results. This can be done -in two ways. -

+
+	set_error_reporting( "basic"|"extended")
+
-
- [val]= lane_h[1] -

-Makes sure lane has finished, and gives its first (maybe only) return value. -Other return values will be available in other lane_h indices. -

-If the lane ended in an error, it is propagated to master state at this place. + Sets the error reporting mode. "basic" is selected by default.

-
- [...]|[nil,err,stack_tbl]= lane_h:join( [timeout_secs] ) -

-Waits until the lane finishes, or timeout seconds have passed. -Returns nil on timeout, nil,err,stack_tbl if the lane hit an error, -nil, "killed" if forcefully killed (starting with v3.3.0), or the return values of the lane. -Unlike in reading the results in table fashion, errors are not propagated. + A lane can be waited upon by simply reading its results. This can be done in two ways. +

-

+
+	[val]= lane_h[1]
+
-
- set_error_reporting("basic"|"extended") -
-

- Sets the error reporting mode. "basic" is selected by default. -

- stack_tbl is a table describing where the error was thrown.
- In extended mode, stack_tbl is an array of tables containing info gathered with lua_getinfo() ("source","currentline","name","namewhat","what").
-In "basic mode", stack_tbl is an array of "<filename>:<line>" strings. Use table.concat() to format it to your liking (or just ignore it). - -

-If you use :join, make sure your lane main function returns -a non-nil value so you can tell timeout and error cases apart from succesful -return (using the .status property may be risky, since it might change -between a timed out join and the moment you read it). -

- -
-
-  require "lanes"
+

+ Makes sure lane has finished, and gives its first (maybe only) return value. Other return values will be available in other lane_h indices. +
+ If the lane ended in an error, it is propagated to master state at this place. +

- f= lanes.gen( function() error "!!!" end ) - a= f(1) +
+	[...]|[nil,err,stack_tbl]= lane_h:join( [timeout_secs] )
+
- --print( a[1] ) -- propagates error +

+ Waits until the lane finishes, or timeout seconds have passed. Returns nil on timeout, nil,err,stack_tbl if the lane hit an error, nil, "killed" if forcefully killed (starting with v3.3.0), or the return values of the lane. + Unlike in reading the results in table fashion, errors are not propagated. +

- v,err= a:join() -- no propagation - if v==nil then - error( "'a' faced error"..tostring(err) ) -- manual propagation - end -
-
+

+ stack_tbl is a table describing where the error was thrown. +
+ In "extended" mode, stack_tbl is an array of tables containing info gathered with lua_getinfo() ("source","currentline","name","namewhat","what"). +
+ In "basic mode", stack_tbl is an array of "<filename>:<line>" strings. Use table.concat() to format it to your liking (or just ignore it). +

+ +

+ If you use :join, make sure your lane main function returns a non-nil value so you can tell timeout and error cases apart from succesful return (using the .status property may be risky, since it might change between a timed out join and the moment you read it). +

+ +

+ +
+	require "lanes".configure()
+
+	f = lanes.gen( function() error "!!!" end)
+	a = f( 1)
+
+	--print( a[1])   -- propagates error
+
+	v, err = a:join()   -- no propagation
+	if v == nil then
+		error( "'a' faced error"..tostring(err))   -- manual propagation
+	end
+

-If you want to wait for multiple lanes to finish (any of a set of lanes), use -a Linda object. Give each lane a specific id, and send -that id over a Linda once that thread is done (as the last thing you do). + If you want to wait for multiple lanes to finish (any of a set of lanes), use a Linda object. Give each lane a specific id, and send that id over a Linda once that thread is done (as the last thing you do).

+
+	require "lanes".configure()
+
+	local sync_linda = lanes.linda()
+	f = lanes.gen( function() dostuff() sync_linda:send( "done", true) end)
+	a = f()
+	b = f()
+	c = f()
+
+	sync_linda:receive( nil, sync_linda.batched, "done", 3) -- wait for 3 lanes to write something in "done" slot of sync_linda
+

Cancelling

-
- bool[,reason]= lane_h:cancel( [timeout_secs=0.0,] [force_kill_bool=false] ) -
-
- - bool= cancel_test() - -
+
+	bool[,reason] = lane_h:cancel( [timeout_secs=0.0,] [force_kill_bool = false] )
+
+ +

+ cancel()sends a cancellation request to the lane. If timeout_secs is non-zero, waits for the request to be processed, or a timeout to occur. + Returns true if the lane was already done (in "done", "error" or "cancelled" status) or if the cancellation was fruitful within timeout period. +

-

cancel()sends a cancellation request to the lane. If timeout_secs is non-zero, waits -for the request to be processed, or a timeout to occur. -Returns true if the lane was already done (in "done", "error" or "cancelled" status) -or if the cancellation was fruitful within timeout period. -

-If the lane is still running and force_kill is true, the -OS thread running the lane is forcefully killed. This means no GC, and should -generally be the last resort. +

+ If the lane is still running after the timeout expired and force_kill is true, the OS thread running the lane is forcefully killed. This means no GC, and should generally be the last resort.

+

-Starting with v3.3.0, if cancel() returns false, it also returns either "timeout" or "killed" as second return value. + Starting with v3.3.0, if cancel() returns false, it also returns either "timeout" or "killed" as second return value.

-

Cancellation is tested before going to sleep in receive() or send() calls -and after executing cancelstep Lua statements. Starting with version 3.0-beta, a pending receive() -or send() call is awakened. This means the execution of the lane will resume although the operation has -not completed, to give the lane a chance to detect cancellation. The code should be able to handle this situation appropriately if required. -It is also possible to manually test for cancel requests with cancel_test(). + +

+ Cancellation is tested before going to sleep in receive() or send() calls and after executing cancelstep Lua statements. Starting with version 3.0-beta, a pending receive()or send() call is awakened. +
+ This means the execution of the lane will resume although the operation has not completed, to give the lane a chance to detect cancellation (even in the case the code waits on a linda with infinite timeout). +
+ The code should be able to handle this situation appropriately if required (in other words, it should gracefully handle the fact that it didn't receive the expected values). +
+ It is also possible to manually test for cancel requests with cancel_test().

@@ -530,24 +727,24 @@ It is also possible to manually test for cancel requests with cancel_test()<

Finalizers

-
- set_finalizer( finalizer_func ) -

- void= finalizer_func( [err, stack_tbl] ) -
+
+	set_finalizer( finalizer_func)
+
+	void = finalizer_func( [err, stack_tbl])
+
-

The error call is used for throwing exceptions in Lua. What Lua -does not offer, however, is scoped finalizers -that would get called when a certain block of instructions gets exited, whether -through peaceful return or abrupt error. +

+ The error call is used for throwing exceptions in Lua. What Lua does not offer, however, is scoped finalizers + that would get called when a certain block of instructions gets exited, whether through peaceful return or abrupt error.

-

Since 2.0.3, Lanes prepares a function set_finalizer for doing this. -Any functions given to it will be called in the lane Lua state, just prior to -closing it. They are not called in any particular order. + +

+ Since 2.0.3, Lanes registers a function set_finalizer in the lane's Lua state for doing this. + Any functions given to it will be called in the lane Lua state, just prior to closing it. It is possible to set more than one finalizer. They are not called in any particular order.

-

An error in a finalizer itself overrides the state of the regular chunk -(in practise, it would be highly preferable not to have errors in finalizers). -If one finalizer errors, the others may not get called. + +

+ An error in a finalizer itself overrides the state of the regular chunk (in practise, it would be highly preferable not to have errors in finalizers). If one finalizer errors, the others may not get called.

@@ -555,195 +752,181 @@ If one finalizer errors, the others may not get called.

Lindas

-

Communications between lanes is completely detached from the lane handles -themselves. By itself, a lane can only provide return values once it's finished, -or throw an error. Needs to communicate during runtime are handled by Linda objects, which are -deep userdata instances. They can be provided to a lane -as startup parameters, upvalues or in some other Linda's message. -

-Access to a Linda object means a lane can read or write to any of its data -slots. Multiple lanes can be accessing the same Linda in parallel. No application -level locking is required; each Linda operation is atomic. -

- -
-
-  require "lanes"
-
-  local linda= lanes.linda()
-
-  local function loop( max )
-    for i=1,max do
-        print( "sending: "..i )
-        linda:send( "x", i )    -- linda as upvalue
-    end
-  end
-
-  a= lanes.gen("",loop)( 10000 )
-
-  while true do
-    local val= linda:receive( 3.0, "x" )    -- timeout in seconds 
-    if val==nil then
-        print( "timed out" )
-        break
-    end
-    print( "received: "..val )
-  end
-
-
+

+ Communications between lanes is completely detached from the lane handles themselves. By itself, a lane can only provide return values once it's finished, or throw an error. + Needs to communicate during runtime are handled by Linda objects, which are + deep userdata instances. They can be provided to a lane as startup parameters, upvalues or in some other Linda's message. +

+

+ Access to a Linda object means a lane can read or write to any of its data slots. Multiple lanes can be accessing the same Linda in parallel. No application level locking is required; each Linda operation is atomic.

-

Characteristics of the Lanes implementation of Lindas are: - -

    -
  • keys can be of boolean, number, string or light userdata type -
  • -
  • values can be any type supported by inter-state copying (same limits - as for function parameters and upvalues) -
  • -
  • consuming method is :receive (not in) -
  • -
  • non-consuming method is :get (not rd) -
  • -
  • two producer-side methods: :send and :set (not out) -
  • -
  • send allows for sending multiple values -atomically- to a - given key -
  • -
  • receive can wait for multiple keys at once -
  • -
  • - receive has a batched mode to consume more than one value from a single key, as in linda:receive( 1.0, linda.batched, "key", 3, 6) -
  • -
  • individual keys' queue length can be limited, balancing speed differences - in a producer/consumer scenario (making :send wait) -
  • -
+ +
+	require "lanes".configure()
+
+	local linda = lanes.linda()
+
+	local function loop( max)
+		for i = 1, max do
+			print( "sending: " .. i)
+			linda:send( "x", i)    -- linda as upvalue
+		end
+	end
+
+	a = lanes.gen( "", loop)( 10000)
+
+	while true do
+		local key, val = linda:receive( 3.0, "x")    -- timeout in seconds
+		if val == nil then
+			print( "timed out")
+			break
+		end
+		print( "received: " .. val)
+	end
+
+ +

+ Characteristics of the Lanes implementation of Lindas are: + +

    +
  • Keys can be of boolean, number, string or light userdata type. Tables and functions can't be keys because their identity isn't preserved when transfered from one Lua state to another.
  • +
  • values can be any type supported by inter-state copying (same limits as for function parameters and upvalues).
  • +
  • consuming method is :receive (not in).
  • +
  • non-consuming method is :get (not rd).
  • +
  • two producer-side methods: :send and :set (not out).
  • +
  • send allows for sending multiple values -atomically- to a given key.
  • +
  • receive can wait for multiple keys at once.
  • +
  • receive has a batched mode to consume more than one value from a single key, as in linda:receive( 1.0, linda.batched, "key", 3, 6).
  • +
  • individual keys' queue length can be limited, balancing speed differences in a producer/consumer scenario (making :send wait).
  • +
+

+ +
+	h = lanes.linda( [opt_name])
+
+	bool = h:send( [timeout_secs,] key, ... )
+
+	[key, val] = h:receive( [timeout_secs,] key [, ...])
+
+	[key, val [, ...]] = h:receive( timeout, h.batched, key, n_uint_min[, n_uint_max])
+
+	void = h:limit( key, n_uint)
+
+ +

+ The send and receive methods use Linda keys as FIFO stacks (first in, first out). Timeouts are given in seconds (millisecond accuracy). If using numbers as the first Linda key, one must explicitly give nil as the timeout parameter to avoid ambiguities.

-
- h= lanes.linda( [opt_name]) -

- bool= h:send( [timeout_secs,] key, ... ) -
- [val, key]= h:receive( [timeout_secs,] key [, ...] ) -

- = h:limit( key, n_uint ) -
+ By default, stack sizes are unlimited but limits can be enforced using the limit method. This can be useful to balance execution speeds in a producer/consumer scenario. +

-

The send and receive methods use Linda keys as FIFO stacks -(first in, first out). Timeouts are given in seconds (millisecond accuracy). -If using numbers as the first Linda key, one must explicitly give nil -as the timeout parameter to avoid ambiguities. -

-By default, stack sizes are unlimited but limits can be -enforced using the limit method. This can be useful to balance execution -speeds in a producer/consumer scenario. -

-Note that any number of lanes can be reading or writing a Linda. There can be -many producers, and many consumers. It's up to you. -

-

send returns true if the sending succeeded, and false -if the queue limit was met, and the queue did not empty enough during the given -timeout. -

-Equally, receive returns a value and the key that provided the value, -or nothing for timeout. Note that nils can be sent and received; -the key value will tell it apart from a timeout. -

-Multiple values can be sent to a given key at once, atomically (the send will -fail unless all the values fit within the queue limit). This can be useful for -multiple producer scenarios, if the protocols used are giving data in streams -of multiple units. Atomicity avoids the producers from garbling each others -messages, which could happen if the units were sent individually. -

- -When receiving from multiple slots, the keys are checked in order, which can -be used for making priority queues. -

- -
- linda_h:set( key, [val] ) -
- [val]= linda_h:get( key ) -
+

+ Note that any number of lanes can be reading or writing a Linda. There can be many producers, and many consumers. It's up to you. +

-

-The table access methods are for accessing a slot without queuing or consuming. -They can be used for making shared tables of storage among the lanes. -

-Writing to a slot overwrites existing value, and clears any possible queued -entries. Table access and send/receive can be used together; -reading a slot essentially peeks the next outcoming value of a queue. -

-

- - - -
- [val]= linda_h:count( [key[,...]]) -
- -

-

- Returns some information about the contents of the linda. -
If no key is specified, and the linda is empty, returns nothing. -
If no key is specified, and the linda is not empty, returns a table of key/count pairs that counts the number of items in each - of the exiting keys of the linda. This count can be 0 if the key has been used but is empty. -
If a single key is specified, returns the number of pending items, or nothing if the key is unknown. -
If more than one key is specified, return a table of key/count pairs for the known keys. -

+

+ send returns true if the sending succeeded, and false if the queue limit was met, and the queue did not empty enough during the given timeout, or the operation was cancelled. +

- +
+	[table] = linda_h:dump()
+
+ +

+ Returns a table describing the full contents of a linda, or nil if the linda wasn't used yet. +

Granularity of using Lindas

-

A single Linda object provides an infinite number of slots, so why would -you want to use several? -

There are some important reasons: - -

    -
  • Access control. If you don't trust certain code completely, or just - to modularize your design, use one Linda for one usage and another one - for the other. This keeps your code clear and readable. You can pass - multiple Linda handles to a lane with practically no added cost. -
  • - -
  • Namespace control. Linda keys have a "flat" namespace, so collisions - are possible if you try to use the same Linda for too many separate uses. -
  • - -
  • Performance. Changing any slot in a Linda causes all pending threads - for that Linda to be momentarily awakened (at least in the C level). - This can degrade performance due to unnecessary OS level context switches. - The more keeper states you declared with lanes.configure() the less - this should be a problem. -
  • -
+

+ A linda is a gateway to read and write data inside some hidden Lua states, called keeper states. Lindas are hashed to a fixed number of keeper states, which are a locking entity. +
+ The data sent through a linda is stored inside the associated keeper state in a Lua table where each linda slot is the key to another table containing a FIFO for that slot. +
+ Each keeper state is associated with an OS mutex, to prevent concurrent access to the keeper state. The linda itself uses two signals to be made aware of operations occuring on it. +
+ Whenever Lua code reads from or writes to a linda, the mutex is acquired. If linda limits don't block the operation, it is fulfilled, then the mutex is released. +
+ If the linda has to block, the mutex is released and the OS thread sleeps, waiting for a linda operation to be signalled. When an operation occurs on the same linda, possibly fufilling the condition, or a timeout expires, the thread wakes up. +
+ If the thread is woken but the condition is not yet fulfilled, it goes back to sleep, until the timeout expires. +
+ When a lane is cancelled, the signal it is waiting on (if any) is signalled. In that case, the linda operation will return no data. +

+ +

+ A single Linda object provides an infinite number of slots, so why would you want to use several? +

+ +

+ There are some important reasons: +

    +
  • + Access control. If you don't trust certain code completely, or just to modularize your design, use one Linda for one usage and another one + for the other. This keeps your code clear and readable. You can pass multiple Linda handles to a lane with practically no added cost. +
  • + +
  • + Namespace control. Linda keys have a "flat" namespace, so collisions are possible if you try to use the same Linda for too many separate uses. +
  • + +
  • + Performance. Changing any slot in a Linda causes all pending threads for that Linda to be momentarily awakened (at least in the C level). + This can degrade performance due to unnecessary OS level context switches. The more keeper states you declared with lanes.configure() the less this should be a problem. +
  • +
+ +On the other side, you need to use a common Linda for waiting for multiple keys. You cannot wait for keys from two separate Linda objects at the same time. +

-On the other side, you need to use a common Linda for waiting for multiple -keys. You cannot wait for keys from two separate Linda objects at the same -time. -

+

Actually, you can. Make separate lanes to wait each, and then multiplex those events to a common Linda, but... :).

@@ -753,77 +936,66 @@ events to a common Linda, but... :).

Timers

-
- = lanes.timer( linda_h, key, date_tbl|first_secs [,period_secs] ) -
+
+	void = lanes.timer( linda_h, key, date_tbl|first_secs [,period_secs])
+

- Timers are implemented as a lane. They can be disabled by setting "with_timers" to nil or false - to lanes.configure(). -

-

-Timers can be run once, or in a reoccurring fashion (period_secs > 0). -The first occurrence can be given either as a date or as a relative delay in seconds. -The date table is like what os.date("*t") returns, in the -local time zone. -

-Once a timer expires, the key is set with the current time -(in seconds, same offset as os.time() but with millisecond accuracy). -The key can be waited upon using the regular Linda :receive() -method. -

-A timer can be stopped simply with first_secs=0|nil and no period. -

- -
-
-  local lanes = require "lanes"
-  lanes.configure( 1)
+	Timers are implemented as a lane. They can be disabled by setting "with_timers" to nil or false to lanes.configure().
+

+ +

+ Timers can be run once, or in a reoccurring fashion (period_secs > 0). The first occurrence can be given either as a date or as a relative delay in seconds. The date table is like what os.date("*t") returns, in the local time zone. +

+ +

+ Once a timer expires, the key is set with the current time (in seconds, same offset as os.time() but with millisecond accuracy). The key can be waited upon using the regular Linda :receive() method. +

- local linda= lanes.linda() +

+ A timer can be stopped simply with first_secs=0|nil and no period. +

- -- First timer once a second, not synchronized to wall clock - -- - lanes.timer( linda, "sec", 1, 1 ) +
+	local lanes = require "lanes"
+	lanes.configure()
 
-  -- Timer to a future event (next even minute); wall clock synchronized 
-  --
-  local t= os.date( "*t", os.time()+60 )    -- now + 1min
-  t.sec= 0
+	local linda = lanes.linda()
 
-  lanes.timer( linda, "min", t, 60 )   -- reoccur every minute (sharp)
+	-- First timer once a second, not synchronized to wall clock
+	--
+	lanes.timer( linda, "sec", 1, 1)
 
-  while true do
-    local v,key= linda:receive( "sec", "min" )
-    print( "Timer "..key..": "..v )
-  end
-
-
+ -- Timer to a future event (next even minute); wall clock synchronized + -- + local t = os.date( "*t", os.time() + 60) -- now + 1min + t.sec = 0 + + lanes.timer( linda, "min", t, 60) -- reoccur every minute (sharp) + + while true do + local key, v = linda:receive( "sec", "min") + print( "Timer "..key..": "..v) + end +
+ +

+ NOTE: Timer keys are set, not queued, so missing a beat is possible especially if the timer cycle is extremely small. The key value can be used to know the actual time passed. +

-

-NOTE: Timer keys are set, not queued, so missing a beat is possible especially -if the timer cycle is extremely small. The key value can be used to know the -actual time passed. -

- - - + + + +
Design note:  - -Having the API as lanes.timer() is intentional. Another -alternative would be linda_h:timer() but timers are not traditionally -seen to be part of Lindas. Also, it would mean any lane getting a Linda handle -would be able to modify timers on it. A third choice could -be abstracting the timers out of Linda realm altogether (timer_h= lanes.timer( date|first_secs, period_secs )) -but that would mean separate waiting functions for timers, and lindas. Even if -a linda object and key was returned, that key couldn't be waited upon simultaneously -with one's general linda events. -The current system gives maximum capabilities with minimum API, and any smoothenings -can easily be crafted in Lua at the application level. - -
Design note: + + Having the API as lanes.timer() is intentional. Another alternative would be linda_h:timer() but timers are not traditionally seen to be part of Lindas. Also, it would mean any lane getting a Linda handle would be able to modify timers on it. + A third choice could be abstracting the timers out of Linda realm altogether (timer_h= lanes.timer( date|first_secs, period_secs )) but that would mean separate waiting functions for timers, and lindas. + Even if a linda object and key was returned, that key couldn't be waited upon simultaneously with one's general linda events. + The current system gives maximum capabilities with minimum API, and any smoothenings can easily be crafted in Lua at the application level. + +
-

@@ -831,46 +1003,43 @@ can easily be crafted in Lua at the application level.

Locks etc.

-Lanes does not generally require locks or critical sections to be used, at all. -If necessary, a limited queue can be used to emulate them. lanes.lua -offers some sugar to make it easy: -

+ Lanes does not generally require locks or critical sections to be used, at all. If necessary, a limited queue can be used to emulate them. lanes.lua offers some sugar to make it easy: +

-
-  lock_func= lanes.genlock( linda_h, key [,N_uint=1] )
+
+	lock_func = lanes.genlock( linda_h, key [,N_uint=1])
 
-  lock_func( M_uint )     -- acquire
-    ..
-  lock_func( -M_uint )    -- release
-
-

+ lock_func( M_uint ) -- acquire + .. + lock_func( -M_uint ) -- release +

-The generated function acquires M entries from the N available, or releases -them if the value is negative. The acquiring call will suspend the lane, if necessary. -Use M=N=1 for a critical section lock (only one lane allowed to enter). -

+

+ The generated function acquires M entries from the N available, or releases them if the value is negative. The acquiring call will suspend the lane, if necessary. Use M=N=1 for a critical section lock (only one lane allowed to enter). +

-Note: The locks generated are not recursive. That would need another -kind of generator, which is currently not implemented. -

+

+ Note: The locks generated are not recursive. That would need another kind of generator, which is currently not implemented. +

-Similar sugar exists for atomic counters: -

+

+ Similar sugar exists for atomic counters: +

-
-  atomic_func= lanes.genatomic( linda_h, key [,initial_num=0.0] )
+

- new_num= atomic_func( [diff_num=+1.0] ) -

-

+
+	atomic_func = lanes.genatomic( linda_h, key [,initial_num=0.0])
 
-Each time called, the generated function will change linda[key]
-atomically, without other lanes being able to interfere. The new value is
-returned. You can use either diff 0.0 or get to just read the current
-value.
-

+ new_num = atomic_func( [diff_num=+1.0]) +

-Note that the generated functions can be passed on to other lanes. +

+ Each time called, the generated function will change linda[key] atomically, without other lanes being able to interfere. The new value is returned. You can use either diff 0.0 or get to just read the current value. +

+ +

+ Note that the generated functions can be passed on to other lanes.

@@ -880,209 +1049,218 @@ Note that the generated functions can be passed on to other lanes.

Limitations on data passing

-

Data passed between lanes (either as starting parameters, return values, upvalues or via Lindas) must conform to the following: +

+ Data passed between lanes (either as starting parameters, return values, upvalues or via Lindas) must conform to the following:

-

    -
  • Booleans, numbers, strings, light userdata, Lua functions and tables of such can always be passed. -
  • -
  • Cyclic tables and/or duplicate references are allowed and reproduced appropriately, - but only within the same transmission. -
      -
    • using the same source table in multiple Linda messages keeps no ties between the tables -
    • -
    -
  • -
  • Objects (tables with a metatable) are copyable between lanes. -
      -
    • metatables are assumed to be immutable; they are internally indexed and only copied once - per each type of objects per lane -
    • -
    -
  • -
  • C functions (lua_CFunction) referring to LUA_ENVIRONINDEX or LUA_REGISTRYINDEX might not - work right in the target -
      -
    • rather completely re-initialize a module with require in the target lane -
    • -
    -
  • -
  • Full userdata can be passed only if it's prepared using the deep userdata - system, which handles its lifespan management -
      -
    • in particular, lane handles cannot be passed between lanes -
    • -
    -
  • -
  • coroutines cannot be passed -
  • -
+ +

+

    +
  • Booleans, numbers, strings, light userdata, Lua functions and tables of such can always be passed.
  • +
  • + Cyclic tables and/or duplicate references are allowed and reproduced appropriately, but only within the same transmission. +
      +
    • Using the same source table in multiple Linda messages keeps no ties between the tables (this is the same reason why tables can't be used as keys).
    • +
    +
  • +
  • + Objects (tables with a metatable) are copyable between lanes. +
      +
    • Metatables are assumed to be immutable; they are internally indexed and only copied once per each type of objects per lane.
    • +
    +
  • +
  • + C functions (lua_CFunction) referring to LUA_ENVIRONINDEX or LUA_REGISTRYINDEX might not work right in the target +
      +
    • Rather completely re-initialize a module with require in the target lane.
    • +
    +
  • +
  • + Full userdata can be passed only if it's prepared using the deep userdata system, which handles its lifespan management +
      +
    • In particular, lane handles cannot be passed between lanes.
    • +
    +
  • +
  • Coroutines cannot be passed. A coroutine's Lua state is tied to the Lua state that created it, and there is no way the mixed C/Lua stack of a couroutine can be transfered from one Lua state to another.
  • +
+

+ + +

Notes about passing C functions

+ +

+ Originally, a C function was copied from one Lua state to another as follows: +

+ +
+	// expects a C function on top of the source Lua stack
+	copy_func( lua_State *dest, lua_State* source)
+	{
+		// extract C function pointer from source
+		lua_CFunction func = lua_tocfunction( source, -1);
+		// transfer upvalues
+		int nup = trasnfer_upvalues( dest, source);
+		// dest Lua stack contains a copy of all upvalues
+		lua_pushcfunction( dest, func, nup);
+	}
+
+ +

+ This has the main drawback of not being LuaJIT-compatible, because some functions registered by LuaJIT are not regular C functions, but specially optimized implementations. As a result, lua_tocfunction() returns NULL for them. +
+ Therefore, Lanes no longer transfers functions that way. Instead, functions are transfered as follows (more or less): +

+ +
+	// expects a C function on top of the source Lua stack
+	copy_func( lua_State *dest, lua_State* source)
+	{
+		// extract C function pointer from source
+		char const* funcname = lookup_func_name( source, -1);
+		// lookup a function bound to this name in the destination state, and push it on the stack
+		push_resolved_func( dest, funcname);
+	}
+
+ +

+ The devil lies in the details: what does "function lookup" mean? +

+ +

+ Since functions are first class values, they don't have a name. All we know for sure is that when a C module registers some functions, they are accessible to the script that required the module through some exposed variables. +
+ For example, loading the string base library creates a table accessible when indexing the global environment with key "string". Indexing this table with "match", "gsub", etc. will give us a function. +
+ When a lane generator creates a lane and performs initializations described by the list of base libraries and the list of required modules, it recursively scans the table created by the initialisation of the module, looking for all values that are C functions. +
+ Each time a function is encountered, the sequence of keys that reached that function is contatenated in a (hopefully) unique name. The [name, function] and [function, name] pairs are both stored in a lookup table in all involved Lua states (main Lua state, keeper states, lanes states). +
+ Then when a function is transfered from one state to another, all we have to do is retrieve the name associated to a function in the source Lua state, then with that name retrieve the equivalent function that already exists in the destination state. +
+ Note that there is no need to transfer upvalues, as they are already bound to the function registered in the destination state. (And in any event, it is not possible to create a closure from a C function pushed on the stack, it can only be created with a lua_CFunction pointer). +

+ +

+ There are two issues here: +

    +
  • Some base libraries register some C functions in the global environment. Because of that, Lanes must scan the global namespace to find all C functions (such as error, print, etc.).
  • +
  • + Nothing prevents a script to create other references to a C function. For example one could do +
    +				string2 = string
    +			
    + When iterating over all keys of the global table, Lanes has no guarantee that it will hit "string" before or after "string2". However, the values associated to string.match and string2.match are the same C function. + Lanes doesn't expect a C function value to be encountered more than once. In the event it occurs, when the lookup table is populated with a [function, name] pair, an existing pair won't be updated if it is already found. In other words, the first name that was computed is retained. + If Lanes processed "string2" first, it means that if the Lua state that contains the "string2" global name sends function string.match, lookup_func_name would return name "string2.match", with the obvious effect that push_resolved_func + won't find "string2.match" in the destination lookup database, thus failing the transfer (even though this function is referenced under name "string.match"). +
  • +
+ Another more direct reason of failed transfer is that the destination state doesn't know about the C function that has to be transferred. This occurs if a function is tranferred in a lane before it had a chance to scan the module. + If the C function is sent through a linda, it is enough for the destination lane body to have required the module before the function is sent. + But if the lane body provided to the generator has a C function as upvalue, the transfer itself must succeed, therefore the module that imported that C function must be required in the destination lane before the lane body starts executing. This is where the .required options play their role.

Required of module makers

-Most Lua extension modules should work unaltered with Lanes. -If the module simply ties C side features to Lua, everything is fine without -alterations. The luaopen_...() entry point will be called separately for each -lane, where the module is require'd from. -

-If it, however, also does one-time C side initializations, these -should be covered into a one-time-only construct such as below. -

+ Most Lua extension modules should work unaltered with Lanes. If the module simply ties C side features to Lua, everything is fine without alterations. The luaopen_...() entry point will be called separately for each lane, where the module is require'd from. +

-
- -
- int luaopen_module( lua_State *L )
- {
-    static char been_here;  /* 0 by ANSI C */
-
-    /* Calls to 'require' serialized by Lanes; this is safe.  
-    */
-    if (!been_here) {
-        been_here= 1;
-        ... one time initializations ...
-    }
-
-    ... binding to Lua ...
- }
-
-
+

+ If it, however, also does one-time C side initializations, these should be covered into a one-time-only construct such as below.

+
+	int luaopen_module( lua_State *L )
+	{
+		static char been_here;  /* 0 by ANSI C */
+
+		// Calls to 'require' serialized by Lanes; this is safe.
+		if (!been_here)
+		{
+			been_here= 1;
+			... one time initializations ...
+		}
+		... binding to Lua ...
+	}
+
+

Deep userdata in your own apps

-The mechanism Lanes uses for sharing Linda handles between separate Lua states -can be used for custom userdata as well. Here's what to do. + The mechanism Lanes uses for sharing Linda handles between separate Lua states can be used for custom userdata as well. Here's what to do.

+
    -
  1. Provide an identity function for your userdata, in C. This function is -used for creation and deletion of your deep userdata (the shared resource), - and for making metatables for the state-specific proxies for accessing it. The - prototype is - - -
    - void idfunc( lua_State *L, char const * const which); -
    -which can be one of: -
      -
    • - "new": requests the creation of a new object, whose pointer is pushed on the stack - as a light userdata. -
    • -
    • - "delete": receives this same pointer on the stack, and should cleanup the object.
    • -
    • - "metatable": should build a metatable for the object. Don't cache the metatable -yourself, Lanes takes care of it ("metatable" should only be invoked once).
    • -
    • - "module": is the name of the module that exports the idfunc, -to be pushed on the stack as a string. It is necessary so that Lanes can require it in -any Lane and keeper state that receives a userdata. This is to prevent crashes in situations -where the module could be unloaded while the idfunc pointer is still held.
    • -
    -Take a look at linda_id in lanes.c. -
  2. -
  3. Instanciate your userdata using luaG_deep_userdata(), - instead of the regular lua_newuserdata(). - Given an idfunc, it sets up the support - structures and returns a state-specific proxy userdata for accessing your - data. This proxy can also be copied over to other lanes. -
  4. -
  5. Accessing the deep userdata from your C code, use luaG_todeep() - instead of the regular lua_touserdata(). -
  6. +
  7. + Provide an identity function for your userdata, in C. This function is used for creation and deletion of your deep userdata (the shared resource), and for making metatables for the state-specific proxies for accessing it. The prototype is +
    +			void idfunc( lua_State *L, char const * const which);
    +		
    + which can be one of: +
      +
    • "new": requests the creation of a new object, whose pointer is pushed on the stack as a light userdata.
    • +
    • "delete": receives this same pointer on the stack, and should cleanup the object.
    • +
    • "metatable": should build a metatable for the object. Don't cache the metatable yourself, Lanes takes care of it ("metatable" should only be invoked once).
    • +
    • "module": is the name of the module that exports the idfunc, to be pushed on the stack as a string. It is necessary so that Lanes can require it in any Lane and keeper state that receives a userdata. This is to prevent crashes in situations where the module could be unloaded while the idfunc pointer is still held.
    • +
    + Take a look at linda_id in lanes.c. +
  8. +
  9. Instanciate your userdata using luaG_deep_userdata(), instead of the regular lua_newuserdata(). Given an idfunc, it sets up the support structures and returns a state-specific proxy userdata for accessing your data. This proxy can also be copied over to other lanes.
  10. +
  11. Accessing the deep userdata from your C code, use luaG_todeep() instead of the regular lua_touserdata().
-

Deep userdata management will take care of tying to __gc methods, -and doing reference counting to see how many proxies are still there for -accessing the data. Once there are none, the data will be freed through a call -to the idfunc you provided. +

+ Deep userdata management will take care of tying to __gc methods, and doing reference counting to see how many proxies are still there for accessing the data. Once there are none, the data will be freed through a call to the idfunc you provided.

-

NOTE: The lifespan of deep userdata may exceed that of the Lua state -that created it. The allocation of the data storage should not be tied to -the Lua state used. In other words, use malloc/free or -similar memory handling mechanism. + +

+ NOTE: The lifespan of deep userdata may exceed that of the Lua state that created it. The allocation of the data storage should not be tied to the Lua state used. In other words, use malloc/free or similar memory handling mechanism.

Lane handles don't travel

-Lane handles are not implemented as deep userdata, and cannot thus be -copied across lanes. This is intentional; problems would occur at least when -multiple lanes were to wait upon one to get ready. Also, it is a matter of -design simplicity. -

-The same benefits can be achieved by having a single worker lane spawn all -the sublanes, and keep track of them. Communications to and from this lane -can be handled via a Linda. + Lane handles are not implemented as deep userdata, and cannot thus be copied across lanes. This is intentional; problems would occur at least when multiple lanes were to wait upon one to get ready. Also, it is a matter of design simplicity. +

+ +

+ The same benefits can be achieved by having a single worker lane spawn all the sublanes, and keep track of them. Communications to and from this lane can be handled via a Linda.

Beware with print and file output

-In multithreaded scenarios, giving multiple parameters to print() -or file:write() may cause them to be overlapped in the output, -something like this: + In multithreaded scenarios, giving multiple parameters to print() or file:write() may cause them to be overlapped in the output, something like this: -

-  A:  print( 1, 2, 3, 4 )
-  B:  print( 'a', 'b', 'c', 'd' )
+
+	A:  print( 1, 2, 3, 4 )
+	B:  print( 'a', 'b', 'c', 'd' )
 
-  1   a   b   2   3   c   d   4
-
+ 1 a b 2 3 c d 4 +
-Lanes does not protect you from this behaviour. The thing to do is either to -concentrate your output to a certain lane per stream, or to concatenate output -into a single string before you call the output function. + Lanes does not protect you from this behaviour. The thing to do is either to concentrate your output to a certain lane per stream, or to concatenate output into a single string before you call the output function.

Performance considerations

-Lanes is about making multithreading easy, and natural in the Lua state of mind. -Expect performance not to be an issue, if your program is logically built. -Here are some things one should consider, if best performance is vital: -

-

    -
  • Data passing (parameters, upvalues, Linda messages) is generally fast, - doing two binary state-to-state copies (from source state to hidden state, - hidden state to target state). Remember that not only the function you - specify but also its upvalues, their upvalues, etc. etc. will get copied. -
  • -
  • Lane startup is fast (1000's of lanes a second), depending on the - number of standard libraries initialized. Initializing all standard libraries - is about 3-4 times slower than having no standard libraries at all. If you - throw in a lot of lanes per second, make sure you give them minimal necessary - set of libraries. -
  • -
  • Waiting Lindas are woken up (and execute some hidden Lua code) each - time any key in the Lindas they are waiting for are changed. This - may give essential slow-down (not measured, just a gut feeling) if a lot - of Linda keys are used. Using separate Linda objects for logically separate - issues will help (which is good practise anyhow). -
  • -
  • Linda objects are light. The memory footprint is two OS-level signalling - objects (HANDLE or pthread_cond_t) for each, plus one - C pointer for the proxies per each Lua state using the Linda. Barely nothing. -
  • -
  • Timers are light. You can probably expect timers up to 0.01 second - resolution to be useful, but that is very system specific. All timers are - merged into one main timer state (see timer.lua); no OS side - timers are utilized. -
  • -
  • Lindas are hashed to a fixed number of "keeper states", which are a locking entity. - If you are using a lot of Linda objects, - it may be useful to try having more of these keeper states. By default, - only one is used (see lanes.configure()). -
  • + Lanes is about making multithreading easy, and natural in the Lua state of mind. Expect performance not to be an issue, if your program is logically built. Here are some things one should consider, if best performance is vital: +

    + +

    +

      +
    • Data passing (parameters, upvalues, Linda messages) is generally fast, doing two binary state-to-state copies (from source state to hidden state, hidden state to target state). Remember that not only the function you specify but also its upvalues, their upvalues, etc. etc. will get copied.
    • +
    • Lane startup is fast (1000's of lanes a second), depending on the number of standard libraries initialized. Initializing all standard libraries is about 3-4 times slower than having no standard libraries at all. If you throw in a lot of lanes per second, make sure you give them minimal necessary set of libraries.
    • +
    • Waiting Lindas are woken up (and execute some hidden Lua code) each time any key in the Lindas they are waiting for are changed. This may give essential slow-down (not measured, just a gut feeling) if a lot of Linda keys are used. Using separate Linda objects for logically separate issues will help (which is good practise anyhow).
    • +
    • Linda objects are light. The memory footprint is two OS-level signalling objects (HANDLE or pthread_cond_t) for each, plus one C pointer for the proxies per each Lua state using the Linda. Barely nothing.
    • +
    • Timers are light. You can probably expect timers up to 0.01 second resolution to be useful, but that is very system specific. All timers are merged into one main timer state (see timer.lua); no OS side timers are utilized.
    • +
    • If you are using a lot of Linda objects, it may be useful to try having more of these keeper states. By default, only one is used (see lanes.configure()).

    @@ -1090,20 +1268,17 @@ Here are some things one should consider, if best performance is vital:

    Cancelling cancel

    -Cancellation of lanes uses the Lua error mechanism with a special lightuserdata -error sentinel. -If you use pcall in code that needs to be cancellable -from the outside, the special error might not get through to Lanes, thus -preventing the Lane from being cleanly cancelled. You should throw any -lightuserdata error further. -

    -This system can actually be used by application to detect cancel, do your own -cancellation duties, and pass on the error so Lanes will get it. If it does -not get a clean cancellation from a lane in due time, -it may forcefully kill the lane. -

    -The sentinel is exposed as lanes.cancel_error, if you wish to use -its actual value. + Cancellation of lanes uses the Lua error mechanism with a special lightuserdata error sentinel. + If you use pcall in code that needs to be cancellable from the outside, the special error might not get through to Lanes, thus preventing the Lane from being cleanly cancelled. + You should throw any lightuserdata error further. +

    + +

    + This system can actually be used by application to detect cancel, do your own cancellation duties, and pass on the error so Lanes will get it. If it does not get a clean cancellation from a lane in due time, it may forcefully kill the lane. +

    + +

    + The sentinel is exposed as lanes.cancel_error, if you wish to use its actual value.

    @@ -1113,21 +1288,20 @@ its actual value.

    Change log

    - See CHANGES. + See CHANGES.


    -

    For feedback, questions and suggestions: -

    +

    + For feedback, questions and suggestions: +

    -


    - -- cgit v1.2.3-55-g6feb