Saltar al contenido principal
Versión: 20 R5 BETA

Signal

Las señales son herramientas que ofrece el lenguaje 4D para gestionar las interacciones y evitar conflictos entre procesos en una aplicación multiproceso. Las señales le permiten asegurarse de que uno o más procesos esperarán a que se complete una tarea específica antes de continuar la ejecución. Todo proceso puede esperar y/o liberar una señal.

Los semáforos también pueden utilizarse para gestionar las interacciones. Semaphores allow you to make sure that two or more processes do not modify the same resource (file, record...) at the same time. Sólo el proceso que define el semáforo puede eliminarlo.

Objeto signal

Una señal es un objeto compartido que debe ser pasado como parámetro a los comandos que llaman o crean trabajadores o procesos.

A 4D.Signal object contains the following built-in methods and properties:

Any worker/process calling the .wait() method will suspend its execution until the .signaled property is true. Mientras espera una señal, el proceso que llama no utiliza ninguna CPU. Esto puede ser muy interesante para el rendimiento en aplicaciones multiproceso. The .signaled property becomes true when any worker/process calls the .trigger() method.

Note that to avoid blocking situations, the .wait() can also return after a defined timeout has been reached.

Signal objects are created with the New signal command.

Trabajar con señales

In 4D, you create a new signal object by calling the New signal command. Once created, this signal must be passed as a parameter to the New process or CALL WORKER commands so that they can modify it when they have finished the task you want to wait for.

  • signal.wait() must be called from the worker/process that needs another worker/process to finish a task in order to continue.
  • signal.trigger() must be called from the worker/process that finished its execution in order to release all others.

Once a signal has been released using a signal.trigger() call, it cannot be reused again. If you want to set another signal, you need to call the New signal command again.

Since a signal object is a shared object, you can use it to return results from called workers/processes, provided that you do not forget to write values within a Use...End use structure (see example).

Ejemplo

 var $signal : 4D.Signal

// Creation of a signal
$signal:=New signal

// call main process and execute OpenForm method
CALL WORKER(1;"OpenForm";$signal)
// do another calculation
...
// Waiting for the end of the process
$signaled:=$signal.wait()

// Processing of the results
$calc:=$signal.result+...

Método OpenForm :

 #DECLARE ($signal : 4D.Signal)  
var $form : Object
$form:=New object("value";0)

// Abrir el formulario
$win:=Open form window("Information";Movable form dialog box)
DIALOG("Information";$form)
CLOSE WINDOW($win)

// Añade un nuevo atributo a su objeto compartido $signal para pasar su resultado al otro proceso:
Use($signal)
$signal.result:=$form.value
End use

// Activar la señal al proceso de espera
$signal.trigger()

Resumen

.description : Text
contains a custom description for the Signal object.
.signaled : Boolean
contains the current state of the Signal object
.trigger( )
sets the signaled property of the signal object to true
.wait( { timeout : Real } ) : Boolean
makes the current process wait until the .signaled property of the signal object to become true or the optional timeout to expire

New signal

Historia
LanzamientoModificaciones
17 R4Añadidos

New signal { ( description : Text ) } : 4D.Signal

ParámetrosTipoDescripción
descriptionText->Descripción para la señal
Result4D.Signal<-Objeto nativo que encapsula la señal

Descripción

The New signal command creates a 4D.Signal object.

Una señal es un objeto compartido que puede ser pasado como parámetro de un worker o proceso a otro worker o proceso, de manera que:

  • el worker/proceso llamado puede actualizar el objeto de la señal después de que se haya completado el procesamiento específico
  • el worker/proceso que llama puede detener su ejecución y esperar hasta que se actualice la señal, sin consumir recursos de la CPU.

Optionally, in the description parameter you can pass a custom text describing the signal. Este texto también puede definirse después de la creación de la señal.

Since the signal object is a shared object, it can also be used to maintain user properties, including the .description property, by calling the Use...End use structure.

Valor devuelto

A new 4D.Signal object.

Ejemplo

Este es un ejemplo típico de un worker que fija una señal:

 var $signal : 4D.Signal
$signal:=New signal("This is my first signal")

CALL WORKER("myworker";"doSomething";$signal)
$signaled:=$signal.wait(1) //wait for 1 second max

If($signaled)
ALERT("myworker finished the work. Result: "+$signal.myresult)
Else
ALERT("myworker has not finished in less than 1s")
End if

The doSomething method could be like:

 #DECLARE ($signal : 4D.Signal)
//any processing
//...
Use($signal)
$signal.myresult:=$processingResult //return the result
End use
$signal.trigger() // The work is finished

.description

Historia
LanzamientoModificaciones
17 R4Añadidos

.description : Text

Descripción

The .description property contains a custom description for the Signal object..

.description can be set at the creation of the signal object or at any moment. Note that since the Signal object is a shared object, any write-mode access to the .description property must be surrounded by a Use...End use structure.

This property is read-write.

.signaled

Historia
LanzamientoModificaciones
17 R4Añadidos

.signaled : Boolean

Descripción

The .signaled property contains the current state of the Signal object. When the signal is created, .signaled is False. It becomes True when the .trigger( ) is called on the object.

Esta propiedad es de solo lectura.

.trigger()

Historia
LanzamientoModificaciones
17 R4Añadidos

.trigger( )

ParámetrosTipoDescripción
No requiere ningún parámetro

Descripción

The .trigger( ) function sets the signaled property of the signal object to true and awakens all workers or processes waiting for this signal.

If the signal is already in the signaled state (i.e., the signaled property is already true), the function does nothing.

.wait()

Historia
LanzamientoModificaciones
17 R4Añadidos

.wait( { timeout : Real } ) : Boolean

ParámetrosTipoDescripción
timeoutReal->Tiempo máximo de espera de la señal en segundos
ResultBoolean<-State of the .signaled property

Descripción

The .wait( ) function makes the current process wait until the .signaled property of the signal object to become true or the optional timeout to expire.

To prevent blocking code, you can pass a maximum waiting time in seconds in the timeout parameter (decimals are accepted).

Warning: Calling .wait( ) without a timeout in the 4D main process is not recommended because it could freeze the whole 4D application.

If the signal is already in the signaled state (i.e. the .signaled property is already true), the function returns immediately, without waiting.

The function returns the value of the .signaled property. Evaluating this value allows knowing if the function returned because the .trigger( ) has been called (.signaled is true) or if the timeout expired (.signaled is false).

The state of a process that waits for a signal is Waiting for internal flag.