The
!beginthread()
Function
SIMPOL provides a multi-threaded program execution environment regardless
of whether or not the target development platform implements support for
multiple threads. Writing programs to use multiple threads can generally be
considered an advanced topic, but in SIMPOL it is fairly straightforward.
All that is necessary to start a new thread is to call the
!beginthread()
function passing the name of the
function where execution should begin. A second optional parameter allows
the user to pass a reference to any type. This will most often be some
type that provides some additional information to the function that would
otherwise not be available. When a new thread is begun the original thread
continues execution without waiting for the results of the new thread. In
SIMPOL a common use of multiple threads can be found in the way that the
tcpsocketserver type works. Each time a connection is made to
the server, a new thread is created that begins execution at the function
that is passed in the listen()
method. Each of the
threads executes concurrently with the others and with the original server
thread.
Another place that will see regular use of threads is the user interface support provided by the window1 type. For each window that is visible (including child windows but not including form controls) a separate thread is required to manage the events for that window. If no thread is provided then the window will appear to be dead, because it will not respond to events.
The first parameter to the function is a reference to the function that should be called. In practice, this will simply be the name of the function but it could also be a function variable that has the function assigned dynamically during program execution. The second parameter is optional, a reference to any type. This parameter is very important since it is the only way to provide access to information about the remainder of the program that may be needed within the function. Remember there are no global variables in SIMPOL.
The biggest problem with having multiple threads all having access to the same object at the same time is when more than one thread wishes to change the value of some property within the object. This is not generally safe since there is no way of knowing which thread is doing what at what time compared with the others. The only safe way to modify values would be to lock the object or some portion of the object. This can be done using the lock1 type. It is provided specifically to facilitate the safe use of common objects by multiple threads concurrently. If one thread wishes to modify a value in a common object it can attempt to lock the lock1 object that is a member of the common object. If that fails, then it needs to wait and try again (retries can also be built into the call to lock). This allows for the safe regulation of access to the common object. For more information about the lock1 type see the "SIMPOL Language Reference".