User`s manual

Dynamic C Users Manual digi.com 151
A while loop accomplishes our goal of blocking on the function call until it returns something other than
busy.
while ((rc = fat_Open( first_part, name, FAT_FILE, FAT_MUST_CREATE,
&file, &alloc)) == -EBUSY);
The second difference from our earlier sample is the statement right before fat_Open():
file.state = 0;
This is required before opening a file when using non-blocking mode in order to indicate that the file is not
in use. Only do this once. After you have opened the file, do not alter the contents of the file structure.
If fat_Open() succeeds we can go into the non-blocking section of the program: three costatements
inside an endless while loop. The benefit of using the non-blocking mode of the FAT file system is real-
ized when using costatements, an extension of Dynamic C that implements cooperative multitasking.
Instead of waiting while a function finishes its execution, the application can accomplish other tasks.
10.2.3.2.1 Costatement that Writes a File
The first costate is named putdata. It waits for one second and then creates a string to timestamp the
entry of a randomly generated number that is then appended to a file.
Note that the always_on keyword is used. This is required when using a named costatement to force it
to execute every time it is encountered in the execution thread (unless it is made inactive by a call to
CoPause()).
It is easy to suspend execution within a costate by using the waitfor keyword. The costate will relin-
quish control if the argument to waitfor (in this case a call to DelaySec()) evaluates to FALSE. The
next time the execution thread reaches putdata, waitfor will be called again. This will go on until
DelaySec() returns TRUE, i.e., when one second has elapsed from the time DelaySec() was first
called from within waitfor.
After the one second delay, the string to write to the file is placed in a buffer and a looping variable and
position pointer are initialized.
Before the buffer contents can be written to a file in the FAT file system, we must ensure that no collisions
occur since there is another costate that will attempt to read the file every ten seconds. A file can not be
read from and written to at the same time. In the following code the waitfor keyword is used with the
global variable filestate (defined at the top of the application) to implement a locking mechanism. As
soon as the file becomes available for putdata, it is marked unavailable for showdata.
while (1){
costate putdata always_on
{
waitfor (DelaySec(1)); // Wait for one second to elapse
sprintf(obuf, "%02d:%02d:%02d -- %6.3f \n", h, m, s, (25.0 * rand()));
ocount = 0;
optr = obuf;