Frontier Tutorials / Working With Threads / Rules of Thread Safety

Rules of Thread Safety

I state these rules from simple to complex. Note that later rules may seem to contradict earlier ones. In this case, the later rule should be followed. Stating the rules this way makes them easier to understand. Otherwise, each rule would be complicated by exceptions and conditions.

First Principles

0
If you only have one possible thread of execution, avoid the complexities of threads and semaphores entirely. Don't become so enamoured of threads that you use them when you don't have to!
1
All the processes that use a semaphore to control access to a given data value must use the same semaphore. Sounds obvious, but it's a common mistake.

Reading a Data Value

2
If you are reading a data value (atomic or non-atomic) that does not change during the execution of your process, you do not need to control access to that data value through a semaphore.
3
If you are reading an atomic data value that may change during the execution of your process, you do not need to control read access to that data value through a semaphore. You may, however, need to control write access; see rules for Writing a Data Value, below.
4
If you are reading a non-atomic data value that may change during the execution of your process, you do need to control both read and write access to that data value through a semaphore. The thread(s) that read the data value must use the same semaphore as the thread(s) that write the value.

Writing a Data Value

5
If there is only one thread of execution that can change a given atomic data value, you do not need to control access to that data value through a semaphore.
6
Even if there is only one thread of execution that can change a given non-atomic data value, you do need to control access to that data value through a semaphore. This corresponds to Rule 4.
7
If more than one thread of execution may attempt to change the same data, you need to control access to that data value through a semaphore to keep the threads from attempting to change the data at the same time.

Share the Wealth

8
In wait loops, call thread.sleepFor so your process doesn't hog the CPU while doing nothing.
9
During intensive processing, occasionally call sys.systemTask to allow other processes to share the CPU.
10
Keep your semaphores locked for as short a time as possible, to allow other processes to efficiently share the controlled resource.

Now let's look at an example where threads are useful.

Tutorial Contents
Working With Threads
What Are Threads?
Semaphores--Traffic Control for Threads
How to Be Thread-Friendly
Rules of Thread Safety
An Example
Frontier's Thread Verbs
Thread Utilities
Glossary of Terms
About the Author