[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Upvalues vs C static variable
- From: Sean Conner <sean@...>
- Date: Fri, 13 Apr 2018 17:28:08 -0400
It was thus said that the Great Albert Chan once stated:
> When to use lua upvalue mechanism instead of simpler C static variable ?
>
> Example, lua 5.4 work-1 math.random :
>
> It uses upvalue to store the 128-bits random state.
> Why not use static uint64_t state[2] ?
To prevent unintentional sharing of data.
Example, a random number generator named spc_rng() (my own special random
number generator) that when seeded with value X will produce the sequence A
-> B -> C -> D ... (why? Perhaps testing purposes or repeatability or what
have you).
Case 1---the state is stored in a static C variable. Your program
instantiates two separate Lua VMs (say, you are using then in different
threads of the program). As each thread runs, there will be calls
interspaced to spc_rnd() between the two threads:
thread-1 A
thread-2 B
thread-1 C
thread-1 D
thread-2 E
thread-1 F
thread-2 G
so thread1 will "see" the sequence "A C D F" and thread2 will "see" the
sequence "B E G".
Case 2---the state is stored as an upvalue. Your program instantiates two
separate Lua VMs. As each thread runs, there will be calls interspaced to
spc_rnd() between the two threads:
thread-1 A
thread-2 A
thread-1 B
thread-1 C
thread-2 B
thread-1 D
thread-2 C
Here, thread1 will "see" the sequence "A B C D" and thread2 will "see" the
sequence "A B C". Which case is important depends upon what you are trying
to do, but in general, case 2 is a safer approach to take since it leads to
less surprises.
-spc