# 14. mt::LockWrite "variablename"

[<<<] [>>>]

Lock mt variable for write protection. While the variable is locked no programs can access it, not even the one that locked the variable.

Usually there is no need to alter the MT variables, as the variables are automatically locked while their value is altered. Locking is needed when a program needs to alter more than one MT variable in a coincise manner. Another possibility is when a program wants to alter a variable and the new value depends on the previous value. As a simplest example is when aprogram wants to increment a variable.

In either case the programs have to have a pseudo MT variable, which is used in the locking and unlocking functions. Usually the programs use these variables only to lock and to release and do not care their values, albeit there is nothing that would prohibit using the values.

For example a program (X) wants to increment the MT variable "B" and it has to keep track of the variable "BB" to ensure that "BB" is the double of "B".

In the meantime another (Y) program wants to decrement "BB" by two and set "B" to the half of "BB" to keep the rule.

Program X:

```mt::GetVariable "B",B
B = B+1
mt::SetVariable "B",B
mt::SetVariable "BB",2*B
```

Program Y:

```mt::GetVariable "BB",BB
BB = BB-2
mt::SetVariable "BB",BB
mt::SetVariable "B",B \ 2
```

The lines of the two programs can execute in any mixed order.

See the following scenario:

• Program X examines B and sees that B is 3 (for example)
• Program Y examines BB and sees that BB is 6.
• Program X increments B to be 4.
• Program Y decrements BB to be 4.
• Program Y sets B to be the half of BB to 2.
• Program X sets the variable BB to the double of B, which is 8 for that program. =end itemize

Instead a variable called "BLCK" has to be used (BLCK is just for example):

Program X:

```mt::LockWrite "BLCK"
mt::GetVariable "B",B
B = B+1
mt::SetVariable "B",B
mt::SetVariable "BB",2*B
mt::UnlockWrite "BLCK"
```

Program Y:

```mt::LockWrite "BLCK"
mt::GetVariable "BB",BB
BB = BB-2
mt::SetVariable "BB",BB
mt::SetVariable "B",B \ 2
mt::UnlockWrite "BLCK"
```

The locking at the start of the critical code segments prevents two programs to enter the critical part at the same time.

[<<<] [>>>]