ILE RPG Programmer's Guide
When you define a variable with the STATIC(*ALLTHREAD) keyword,
you are responsible for ensuring that the variable is used in a thread-safe
way. Depending on the scope of the variable and usage of the variable,
you may need to have additional variables to help synchonize access
to the variables:
- If the variable is local to a serialized procedure, then only
one thread can access the variable at one time due to the serialization,
so you do not need to add any extra synchronization for it.
- If the variable is global to the module, and you can guarantee
that it is changed in only one place in your code, and you can further
guarantee that the code that changes the variable will run before
any other thread can use the variable, then you do not need to add
any synchronization for the variable.
- Otherwise, you must add an additional variable to be used with
a synchronization technique such as a mutex or a semaphore. See information
about Threads at: http://www.ibm.com/systems/infocenter/
and in Using thread-related APIs.
If you need to add a synchronization variable to synchronize access
to another variable you must ensure the following:
- The synchronization variable must be initialized before the variable
is ever accessed.
- Whenever you work with the variable, you must first gain access
to it, by locking the semaphore or mutex; when you are finished working
with the variable, you must unlock the semaphore or mutex.
- If the variable is exported from the module, you must ensure that
all modules that import the variable can also use the the synchronization
variable. You can do this by exporting the synchronization variable,
or by adding exported lock and unlock procedures in your exporting
module that can be called by any module that needs to use the variable.
Tip: Establish a naming convention for your variables
that require synchronization and for their synchronization variables
or lock and unlock procedures. Your convention might be to prefix
a variable that requires synchronization with SN_, and to use the
same name for its synchronization variable or procedures, but with
different prefixes. For example, variable SN_nextIndex might have
lock and unlock procedures LOCK_nextIndex and UNLOCK_nextIndex. By
using such a convention, and by rigidly enforcing its use, you can
reduce the possibility that a programmer will use a variable that
requires synchronization without observing the correct synchronization
protocol.
- You must avoid deadlock situations. For example, if one thread
has a lock for FLD1 and tries to obtain a lock for FLD2, while another
thread has a lock on FLD2 and tries to obtained a lock on FLD1, then
both threads will wait forever.
[ Top of Page | Previous Page | Next Page | Contents |
Index ]