5 Designing Tasks
5-38
NJ-series CPU Unit Software User’s Manual (W501)
Use the task exclusive control instructions (i.e., the Lock and Unlock instructions) when it is neces-
sary to write the value of a global variable from more than one task while maintaining concurrency in
the value of the variable. The task exclusive control instructions create a lock region from one Lock
instruction to the next Unlock instruction. If a lock region in one task is being executed, the lock
regions with the same lock number in other tasks are not executed. If you place the instructions that
write to the global variable in lock regions, the concurrency of the value is maintained even if you
write the value of the variable from more than one task.
Refer to information on the Lock and Unlock instructions in the NJ-series Instructions Reference
Manual (Cat. No. W502) for details.
Example:
In this example, task A and task B both have lock region 1. The priority of task B is higher than the
priority of task A. If the execution condition for task B is met during execution of lock region 1 in task
A, execution of task A is paused during lock region 1 and task B is executed. However, in this case,
lock region 1 in task A is not completed, so task B is paused before it processes lock region 1. When
task B is paused, execution of lock region 1 in task A is started again.
When execution of lock region 1 in task A is completed, task A is paused again and the remainder of
lock region 1 in task B is executed. The concurrency of the value of the global variable is maintained
by implementing exclusive control of the write processing of the global variable between the tasks.
• Do not make the locked regions any longer than necessary. If the lock regions are too long, the
task execution period may be exceeded.
• Always use the Lock and Unlock instructions in a pair in the same section of the same POU.
Method 2: Task Exclusive Control Instructions
Unlock instruction
Lock region 1
Unlock instruction
Lock region 1
Executed.
Executed.
Executed.
Global variable
Task A
Higher priority
Lock instruction
Program
Task B
Execution is not
started until
execution of region
1 in task A is
completed.
Lock instruction
Program
Refreshed.
Program
Lock instruction
Unlock instruction
Lock region 1
Program
Lock instruction
Unlock instruction
Lock region 1
Executed.
Global variable
Task A
Task B
Refreshed.