Threads and states in Lua

Source: Internet
Author: User
Tags lua

1. Overview
Thread as a basic data type in Lua, which represents a separate thread of execution (independent threads of execution), the thread type is the basis of the Implementation Association (COROUTINES). Note that the thread type here is not confused with the operating system thread, and Lua's thread type is a data type implemented by the LUA virtual machine.
From the Lua script, a process is a thread type, such as:
Local CO = coroutine.create (function () print ("HI") end) print (CO)  --OUTPUT:THREAD:0038BEE0
To be precise, the process is a thread plus a good set of operating interfaces.
From an implementation perspective, a thread-type data is a stack of Lua-to-c interactions, each containing a function call chain and data stack, as well as a separate debug hook and error message. The stacks that LUA interacts with C can refer to an article previously written. The thread type data is similar to the table data type, and it needs to be managed by a GC.
When calling most functions in the LUA C API, these functions are on a specific stack (or thread), so in many APIs the first parameter is lua_state* (the data structure corresponding to the thread type is lua_state, or the stack of interactions is a struct lua_ State), this parameter not only represents a LUA status, but also represents a thread that is logged in that state. Note that the state here is only one for a virtual machine, and a virtual machine can include multiple threads (or interactive stacks). This state is the global state of the virtual machine, and we can create the state of a virtual machine by calling the function Lual_newstate (), which is declared as follows:
Lua_state *lua_newstate (Lua_alloc F, void *ud);
Yes, in applications (such as in C + +), the first function to invoke is to initialize the virtual machine in order to load and execute the LUA script. This function initializes the state of the virtual machine, or creates the first thread (called the main thread) of the entire virtual machine, or the first interaction stack. In order to create a new thread (or interaction stack) in the already initialized global state, the function lua_newthread can be called, which is declared as follows:

Lua_state *lua_newthread (lua_state *l);
Creating a thread has a separate execution stack, but it is sharing the global state of the virtual machine with its thread. There is no function in Lua to close or destroy a thread, and to create a thread-type data that, like other GC objects, is managed by the virtual machine.

In summary, a LUA virtual machine has only one global state, but can contain multiple execution environments (or multiple threads, interaction stacks, from a scripting point of view, or multiple co-processes), which means that multiple execution environments share a global state. As shown in the following:


The following will look at the data structure of the global state through the source of Lua 5.2.1 Global_state and the related contextual structure lua_state of the script execution, as well as the implementation of the function lua_newstate and Lua_newthread.


2. Source Code Implementation
The first to analyze the global state of the struct Global_state code (lstate.h):

109 */* Global stat                                                                                                 E ', shared by all threads of this state 111 */                                                                      global_state typedef struct {  113 Lua_alloc Frealloc;         /* function to reallocate memory */*ud void;  /* Auxiliary data to ' frealloc ' */Lu_mem totalbytes;  /* Number of bytes currently ALLOCATED-GCDEBT */L_mem gcdebt;  /* Bytes allocated not yet compensated by the collector */117 Lu_mem Gcmemtrav;  /* Memory traversed by the GC */118 Lu_mem gcestimate; /* Estimate of the non-garbage memory in use */119 stringtable STRT;                                                                               /* Hash table for Strings */TValue l_registry;  121 unsigned int seed;                                                                            /* Randomized seed for hashes */122 lu_byte currentwhite;  123 Lu_byte Gcstate;  /* State of garbage collector */124 lu_byte Gckind;  /* Kind of GC running */Lu_byte gcrunning;  /* True if GC is running */126 int SWEEPSTRGC;  /* Position of sweep in ' strt ' */127 gcobject *ALLGC;  /* List of all collectable objects */Gcobject *finobj; /* List of CollectAble objects with finalizers */129 gcobject **SWEEPGC;  /* Current position of sweep in list ' ALLGC ' */Gcobject **sweepfin;  /* Current position of sweep in list ' finobj ' */131 gcobject *gray;  /* List of Gray objects */Gcobject *grayagain;  /* List of objects to be traversed atomically */133 gcobject *weak;  /* List of tables with weak values */134 gcobject *ephemeron;  /* List of Ephemeron tables (weak keys) */135 gcobject *allweak;  /* List of All-weak tables */136 gcobject *TOBEFNZ;  /* List of UserData to be GC */137 upval uvhead; /* Head of double-linked List of all open Upvalues */138 Mbuffer Buff  /* Temporary buffer for string concatenation */139 int gcpause;  /* Size of pause between successive GCs */140 int gcmajorinc;  /* How much to wait for a major GC (only in gen mode) */141 int gcstepmul;  /* GC ' granularity ' */142 lua_cfunction panic;  /* To is called in unprotected errors */143 struct lua_state *mainthread;144 const lua_number *version;  /* Pointer to version number */145 tstring *memerrmsg;  /* Memory-error message */146 tstring *tmname[tm_n];  /* Array with tag-method names */147 struct Table *mt[lua_numtags]; /* Metatables for basic types */148} global_state;
A LUA virtual machine has only one global global_state, which, when called Lua_newstate, creates and initializes the global structure, which manages the globally unique information in Lua, mainly including the following information:
Lua_alloc Frealloc: Virtual machine memory allocation policy, you can specify parameters when calling Lua_newstate, modify the policy, or call the Lual_newstate function to use the default memory allocation policy. You can also set a memory allocation policy by using the function LUA_SETALLOCF:
Stringtable STRT: A global string hash table that holds those short strings so that the entire virtual machine has only one instance of the short string.
TValue L_registry: Save the Global Registry, the registry is a global table (that is, the entire virtual machine has only one registry), it can only be accessed by the C code, typically, it is used to save the data that needs to be shared in several modules. For example, a meta-table created by Lual_newmetatable is placed in the Global registry.
Lua_cfunction Panic: This function is called when there is no error (unprotected errors). This function can be modified by lua_atpanic.
Upval Uvhead: Points to the head that holds all open upvalues doubly linked lists.
struct table *mt[lua_numtags]: Save the primitive type of the meta table, note that both table and UserData have their own meta tables.
struct Lua_state *mainthread: Point to the main lua_state, or the main thread, the master execution stack. Lua virtual machines also create a main thread when calling function Lua_newstate to initialize global state global_state.Of course, you can call Lua_newthread to create a new thread as needed, but the entire virtual machine has only one global state global_state.
The other members of the global State structure are basically related to memory management and GC.
The following is the implementation of the thread corresponding data structure lua_state, the code is as follows (lstate.h):
151/*152 * * ' per thread ' state153 */154 struct lua_state {155 commonheader;156 lu_byte status;157 stkid top;  /* First free slots in the stack */158 global_state *l_g;159 callinfo *ci;  /* Call info for the current function */160 const instruction *OLDPC;  /* Last PC traced */161 Stkid stack_last;  /* Last free slots in the stack */162 stkid stack;  /* Stack base */163 int stacksize;164 unsigned short nny;  /* Number of non-yieldable calls in stacks */165 unsigned short nccalls; /* Number of nested C calls */166 lu_byte hookmask;167 lu_byte allowhook;168 int basehookcount;169 int hookcount;1  Lua_hook hook;171 Gcobject *openupval;  /* List of open upvalues in this stack */172 gcobject *gclist;173 struct lua_longjmp *errorjmp;  /* Current error recover point */174 ptrdiff_t errfunc;  /* Current error handling function (stack index) */175 callinfo base_ci; /* Callinfo for First level (C calling Lua) */176};

As you can see, lua_state structure with other recyclable data type types, structs with Commonheader headers, and it also GC reclaims one of the objects. It mainly includes the following member information:
Lu_byte Status: The state of the thread script, the thread may be in the following state (LUA.H):

*/* Thread status */#define LUA_OK      0 #define Lua_yield   1 #define Lua_errrun  2 #define Lua_errsy Ntax   3 #define LUA_ERRMEM  4 #define LUA_ERRGCMM 5 Wuyi #define LUA_ERRERR  6
  Global_state *l_g: Point to the global State;
The other members are mainly related to the data stack and function call stack, which is also the main information in the lua_state structure. There are also members ptrdiff_t Errfunc is related to error handling functions, that is, each call stack has independent error handling functions, as well as debugging related Lua_hook Hook members.


3. Summary
When invoking Lua_newstate to initialize a LUA virtual machine, a global state and a thread (or call stack) are created, and the global state is unique across the entire VM and shared by other threads. A LUA virtual machine can include multiple threads that share a global state, and the Lua_xmove function can be called between threads to exchange data.


Resources

http://www.cnblogs.com/ringofthec/archive/2010/11/09/lua_State.html Lua API applet 3 (LUA virtual machine initialization)
http://blog.aliyun.com/795 LUA data structure-lua_state (vi)
Lua 5.2.1 Source

Threads and states in Lua

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.