Copyright (c) Hyperion Entertainment and contributors.

Difference between revisions of "Exec Signals"

From AmigaOS Documentation Wiki
Jump to navigation Jump to search
Line 220: Line 220:
 
The following chart gives a brief description of the Exec functions that control task signalling. See the SDK for details about each call.
 
The following chart gives a brief description of the Exec functions that control task signalling. See the SDK for details about each call.
   
  +
{| class="wikitable"
<table>
 
  +
! Exec Signal Function
<tr class="header">
 
  +
! Description
<th align="left">'''Exec Signal Function'''</th>
 
  +
|-
<th align="left">'''Description'''</th>
 
  +
| AllocSignal()
</tr>
 
  +
| Allocate a signal bit.
<tr class="odd">
 
  +
|-
<td align="left">AllocSignal()</td>
 
  +
| FreeSignal()
<td align="left">Allocate a signal bit.</td>
 
  +
| Free a signal bit allocated with AllocSignal().
</tr>
 
  +
|-
<tr class="even">
 
  +
| SetSignal()
<td align="left">FreeSignal()</td>
 
  +
| Query or set the state of the signals for the current task.
<td align="left">Free a signal bit allocated with AllocSignal().</td>
 
  +
|-
</tr>
 
  +
| Signal()
<tr class="odd">
 
  +
| Signal a task by setting signal bits in its Task structure.
<td align="left">SetSignal()</td>
 
  +
|-
<td align="left">Query or set the state of the signals for the current task.</td>
 
  +
| Wait()
</tr>
 
  +
| Wait for one or more signals from other tasks or interrupts.
<tr class="even">
 
  +
|}
<td align="left">Signal()</td>
 
<td align="left">Signal a task by setting signal bits in its Task structure.</td>
 
</tr>
 
<tr class="odd">
 
<td align="left">Wait()</td>
 
<td align="left">Wait for one or more signals from other tasks or interrupts.</td>
 
</tr>
 
</table>
 

Revision as of 23:22, 17 May 2012

Codereview.png Code samples on this page are not yet updated to AmigaOS 4.x some of them may be obsolete or incompatible with AmigaOS 4.x.

Exec Signals

Tasks often need to coordinate with other concurrent system activities (like other tasks and interrupts). This coordination is handled by Exec through the synchronized exchange of specific event indicators called signals.

This is the primary mechanism responsible for all inter-task communication and synchronization on the Amiga. This signal mechanism operates at a low level and is designed for high performance. Signals are used extensively by the Exec message system as a way to indicate the arrival of an inter-task message. The message system is described in more detail in Exec Messages and Ports.

Not for Beginners. This section concentrates on details about signals that most applications do not need to understand for general Amiga programming. For a general overview of signals, see Introduction to Exec.

The Signal System

The signal system is designed to support independent simultaneous events, so several signals can occur at the same time. Each task has 32 independent signals, 16 of which are pre-allocated for use by the operating system. The signals in use by a particular task are represented as bits in a 32-bit field in its Task structure (<exec/tasks.h>). Two other 32-bit fields in the Task structure indicate which signals the task is waiting for, and which signals have been received.

Signals are task relative. A task can only allocate its own signals, and may only wait on its own signals. In addition, a task may assign its own significance to a particular signal. Signals are not broadcast to all tasks; they are directed only to individual tasks. A signal has meaning to the task that defined it and to those tasks that have been informed of its meaning.

For example, signal bit 12 may indicate a timeout event to one task, but to another task it may indicate a message arrival event. You can never wait on a signal that you did not directly or indirectly allocate yourself, and any other task that wishes to signal you must use a signal that you allocated.

Signal Allocation

As mentioned above, a task assigns its own meaning to a particular signal. Because certain system libraries may occasionally require the use of a signal, there is a convention for signal allocation. It is unwise ever to make assumptions about which signals are actually in use.

Before a signal can be used, it must be allocated with the AllocSignal() function. When a signal is no longer needed, it should be freed for reuse with FreeSignal().

BYTE AllocSignal( LONG signalNum );
VOID FreeSignal( LONG signalNum );

AllocSignal() marks a signal as being in use and prevents the accidental use of the same signal for more than one event. You may ask for either a specific signal number, or more commonly, you would pass -1 to request the next available signal. The state of the newly allocated signal is cleared (ready for use). Generally it is best to let the system assign you the next free signal. Of the 32 available signals, the lower 16 are reserved for system use. This leaves the upper 16 signals free for application programs to allocate. Other subsystems that you may call depend on AllocSignal().

The following example asks for the next free signal to be allocated for its use:

if (-1 == (signal = IExec->AllocSignal(-1)))
    IDOS->Printf("no signal bits available\n");
else
    {
    IDOS->Printf("allocated signal number %ld\n", signal);
    /* Other code could go here */
    IExec->FreeSignal(signal)
    }

The value returned by AllocSignal() is a signal bit number. This value cannot be used directly in calls to signal-related functions without first being converted to a mask:

mask = 1L << signal;

It is important to realize that signal bit allocation is relevant only to the running task. You cannot allocate a signal from another task. Note that functions which create a signal MsgPort will allocate a signal from the task that calls the function. Such functions include OpenWindow() and AllocSysObject(). For this reason, only the creating task may Wait() (directly or indirectly) on the MsgPort's signal. Functions which call Wait() include DoIO(), WaitIO() and WaitPort().

Waiting for a Signal

Signals are most often used to wake up a task upon the occurrence of some external event. Applications call the Exec Wait() function, directly or indirectly, in order to enter a wait state until some external event triggers a signal which awakens the task.

Though signals are usually not used to interrupt an executing task, they can be used this way. Task exceptions, described in Exec Interrupts, allow signals to act as a task-local interrupt.

The Wait() function specifies the set of signals that will wake up the task and then puts the task to sleep (into the waiting state).

ULONG Wait( ULONG signalSet );

Any one signal or any combination of signals from this set are sufficient to awaken the task. Wait() returns a mask indicating which signals satisfied the Wait() call. Note that when signals are used in conjunction with a message port, a set signal bit does not necessarily mean that there is a message at the message port.

See Exec Messages and Ports for details about proper handling of messages.

Because tasks (and interrupts) normally execute asynchronously, it is often possible to receive a particular signal before a task actually Wait()s for it. In such cases the Wait() will be immediately satisfied, and the task will not be put to sleep.

The Wait() function implicitly clears those signal bits that satisfied the wait condition. This effectively resets those signals for reuse. However, keep in mind that a task might get more signals while it is still processing the previous signal. If the same signal is received multiple times and the signal bit is not cleared between them, some signals will go unnoticed.

Be aware that using Wait() will break a Forbid() or Disable() state. Wait() cannot be used in supervisor mode or within interrupts.

A task may Wait() for a combination of signal bits and will wake up when any of the signals occur. Wait() returns a signal mask specifying which signal or signals were received. Usually the program must check the returned mask for each signal it was waiting on and take the appropriate action for each that occurred. The order in which these bits are checked is often important.

Here is a hypothetical example of a process that is using the console and timer devices, and is waiting for a message from either device and a possible break character issued by the user:

uint32 consoleSignal = 1L << ConsolePort->mp_SigBit;
uint32 timerSignal   = 1L << TimerPort->mp_SigBit;
uint32 userSignal    = SIGBREAKF_CTRL_C;    /* Defined in <dos/dos.h> */
 
uint32 signals = IExec->Wait(consoleSignal | timerSignal | userSignal);
 
if (signals & consoleSignal)
    IDOS->Printf("new character\n");
 
if (signals & timeOutSignal)
    IDOS->Printf("timeout\n");
 
if (signals & userSignal)
    IDOS->Printf("User Ctrl-C Abort\n");

This code will put the task to sleep waiting for a new character, or the expiration of a time period, or a Ctrl-C break character issued by the user. Notice that this code checks for an incoming character signal before checking for a timeout. Although a program can check for the occurrence of a particular event by checking whether its signal has occurred, this may lead to busy wait polling. Such polling is wasteful of the processor and is usually harmful to the proper function of the Amiga system. However, if a program needs to do constant processing and also check signals (a compiler for example) SetSignal(0,0) can be used to get a copy of your task's current signals.

ULONG SetSignal( ULONG newSignals, ULONG signalSet );

SetSignal() can also be used to set or clear the state of the signals. Implementing this can be dangerous and should generally not be done. The following fragment illustrates a possible use of SetSignal().

uint32 signals = SetSignal(0,0);           /* Get current state of signals */
 
if (signals & SIGBREAKF_CTRL_C)            /* Check for Ctrl-C.           */
    {
    IDOS->Printf("Break\n");               /* Ctrl-C signal has been set. */
    IExec->SetSignal(0, SIGBREAKF_CTRL_C)  /* Clear Ctrl-C signal.        */
    }

Generating a Signal

Signals may be generated from both tasks and system interrupts with the Signal() function.

VOID Signal( struct Task *task, ULONG signalSet );

For example Signal(tc,mask) would signal the task with the specified mask signals. More than one signal can be specified in the mask. The following example code illustrates Wait() and Signal().

;/* signals.c - Execute me to compile me with SAS C 5.10
LC -b1 -cfistq -v -y -j73 signals.c
Blink FROM LIB:c.o,signals.o TO signals LIBRARY LIB:LC.lib,LIB:Amiga.lib
quit
*/

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/alib_protos.h>
#include "stdio.h"

#ifdef LATTICE
int CXBRK(void) { return(0); }     /* Disable Lattice CTRL/C handling */
int chkabort(void) { return(0); }  /* really */
#endif

static UBYTE *VersTag = "$VER: signals 37.1 (28.3.91)";

void subtaskcode(void);    /* prototype for our subtask routine */

LONG  mainsignum = -1;
ULONG mainsig, wakeupsigs;
struct Task *maintask = NULL, *subtask = NULL;
UBYTE subtaskname[] = "RKM_signal_subtask";

void main(int argc, char **argv)
{
BOOL Done = FALSE, WaitingForSubtask = TRUE;

/* We must allocate any special signals we want to receive. */
mainsignum = AllocSignal(-1);
if(mainsignum == -1)
    printf("No signals available\n");
else
    {
    mainsig = 1L << mainsignum;    /* subtask can access this global */
    maintask = FindTask(NULL);     /* subtask can access this global */

    printf("We alloc a signal, create a task, wait for signals\n");
    subtask = CreateTask(subtaskname, 0L, subtaskcode, 2000);
    if(!subtask)
        printf("Can't create subtask\n");
    else
        {
        printf("After subtask signals, press CTRL-C or CTRL-D to exit\n");

        while((!Done)||(WaitingForSubtask))
            {
            /* Wait on the combined mask for all of the signals we are
             * interested in.  All processes have the CTRL_C thru CTRL_F
             * signals.  We're also Waiting on the mainsig we allocated
             * for our subtask to signal us with.  We could also Wait on
             * the signals of any ports/windows our main task created ... */

            wakeupsigs = Wait(mainsig | SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_D);

            /* Deal with all signals that woke us up - may be more than one */
            if(wakeupsigs & mainsig)
                {
                printf("Signalled by subtask\n");
                WaitingForSubtask = FALSE;   /* OK to kill subtask now */
                }
            if(wakeupsigs & SIGBREAKF_CTRL_C)
                {
                printf("Got CTRL-C signal\n");
                Done = TRUE;
                }
            if(wakeupsigs & SIGBREAKF_CTRL_D)
                {
                printf("Got CTRL-D signal\n");
                Done = TRUE;
                }
            }
        Forbid();
        DeleteTask(subtask);
        Permit();
        }
    FreeSignal(mainsignum);
    }
}

void subtaskcode(void)
    {
    Signal(maintask,mainsig);
    Wait(0L);    /* safe state in which this subtask can be deleted */
    }

Function Reference

The following chart gives a brief description of the Exec functions that control task signalling. See the SDK for details about each call.

Exec Signal Function Description
AllocSignal() Allocate a signal bit.
FreeSignal() Free a signal bit allocated with AllocSignal().
SetSignal() Query or set the state of the signals for the current task.
Signal() Signal a task by setting signal bits in its Task structure.
Wait() Wait for one or more signals from other tasks or interrupts.