AYUDA EN LÍNEA
 WINDEVWEBDEV Y WINDEV MOBILE

Este contenido se ha traducido automáticamente.  Haga clic aquí  para ver la versión en inglés.
Ayuda / WLanguage / Funciones WLanguage / Funciones estándar / Funciones de gestión de procesos / Hilos, semáforos, señales y mutex
  • Characteristics of a thread created in WLanguage
  • Thread and HFSQL
  • Characteristics of WLanguage procedure
  • Lifecycle of a thread
  • Error management
  • Procesos no permitidos
WINDEV
WindowsLinuxUniversal Windows 10 AppJavaReportes y ConsultasCódigo de Usuario (UMC)
WEBDEV
WindowsLinuxPHPWEBDEV - Código Navegador
WINDEV Mobile
AndroidWidget Android iPhone/iPadIOS WidgetApple WatchMac CatalystUniversal Windows 10 App
Otros
Procedimientos almacenados
Starts the execution of a secondary thread. The statement is a non-locking statement: the two processes are run in parallel.
Reminder: A thread is a process run in parallel with the current application (main thread). For example, it is possible to launch the execution of a task being processed by Background (backup, etc.).
Ejemplo
// Exécution d'un thread avec passage de paramètres 
sDate is string 
sDate = DateSys()
// Exécution du thread
ThreadExecute("THREADNAME", threadNormal, "pExecReq", (sDate))
// ---------------------------------------------------------
// Détail de la procédure "pExecReq" 
// Cette procédure attend une date en paramètre d'une requête 
PROCEDURE pExecReq(sDate)
IF HExecuteQuery(Sup_Date, hQueryDefault, sDate) = False THEN
	Error(HErrorInfo())
ELSE
	HReadFirst(Sup_Date)
END
// Syntaxe compatible
ThreadExecute("Thread1", threadNormal, ProcédureThread) 
...
// Appel d'une méthode globale d'une classe
ThreadExecute("Thread2", threadNormal, CClasse::MéthodeGlobale)
Sintaxis
WEBDEV - Código Servidor

Declaring and executing a Thread variable Ocultar los detalles

<Result> = ThreadExecute(<WLanguage procedure> [, <Parameters>] [, <Options>])
<Result>: Thread variable
Thread variable corresponding to the thread executed.
<WLanguage procedure>: Procedure name
Name of the WLanguage procedure run. This procedure is run in parallel with the application.
<Parameters>: List of values enclosed in brackets and separated by commas
Parameters of procedure to run. This list of parameters has the following format:
(<Paramètre 1>, ..., <Paramètre N>)
where:
  • <Parameter 1>: First procedure parameter.
  • ...
  • <Parameter N>: Nth procedure parameter.
Caution: Parameters are passed by value. In the case of variables of complex types (arrays, object), the value is the element itself.. To protect access to this Variable, you can use one of the following solutions:
<Options>: Optional constant
Mode for starting the thread.
threadFullCopyHFSQLContext
(Default value)
Triggers the immediate copy of the current HFSQL context.
Recommended if the thread must take into account the current positions in the files and queries of caller context.
threadGlobalContextForces the use of the global context of the project if the thread is run from a window. The thread will continue to run until the application is closed.
The window context is used by default, therefore the thread is stopped when closing the window.
Remark: If ThreadExecute is used in a global initialization code (project, class or set) or from any procedure or method called from a global initialization code, this constant has no effect.
threadLightCopyHFSQLContextTriggers the immediate copy of a part of the current HFSQL context.
Only the directories containing the data files in HFSQL Classic mode and/or the connections in HFSQL Client/Server mode are stored.
threadNormalStarts the thread in normal mode. The HFSQL context is copied the first time an HFSQL feature is used.
threadSecureStarts a thread in secure mode. In this mode, an exception will be thrown:
  • if the thread accesses the controls at runtime,
  • if the ThreadStop function is called.
When the window that triggered the thread is closed, a request to stop the thread is generated (but the thread continues to run after the window is closed).
threadWaitForStartWaits for the actual start of the thread before continuing the execution.
WEBDEV - Código Servidor

Executing a thread already described (Thread variable) Ocultar los detalles

<Result> = ThreadExecute(<Thread>)
<Result>: Thread variable
Thread variable corresponding to the thread executed.
<Thread>: Thread variable
Name of the Thread variable corresponding to the thread to execute.
Caution: If the thread is already being executed or has already been executed, a WLanguage error will appear.

Executing a thread by naming it (Compatible syntax) Ocultar los detalles

ThreadExecute(<Thread name> , <Options> , <WLanguage procedure> [, <Parameter 1> [... [, <Parameter N>]]])
<Thread name>: Character string
Name that will be given to the thread. This name will be used by all thread functions. This name cannot correspond to an empty string ("")
<Options>: Constant
Mode for starting the thread.
threadFullCopyHFSQLContext
(Default value)
Triggers the immediate copy of the current HFSQL context.
Recommended if the thread must take into account the current positions in the files and queries of caller context.
threadGlobalContextForces the use of the global context of the project if the thread is run from a window. The thread will continue to run until the application is closed.
The window context is used by default, therefore the thread is stopped when closing the window.
Remark: If ThreadExecute is used in a global initialization code (project, class or set) or from any procedure or method called from a global initialization code, this constant has no effect.
threadLightCopyHFSQLContextTriggers the immediate copy of a part of the current HFSQL context.
Only the directories containing the data files in HFSQL Classic mode and/or the connections in HFSQL Client/Server mode are stored.
threadNormalStarts the thread in normal mode. The HFSQL context is copied the first time an HFSQL feature is used.
threadSecureStarts a thread in secure mode. In this mode, an exception will be thrown:
  • if the thread accesses the controls at runtime,
  • if the ThreadStop function is called.
When the window that triggered the thread is closed, a request to stop the thread is generated (but the thread continues to run after the window is closed).
threadWaitForStartWaits for the actual start of the thread before continuing the execution.
<WLanguage procedure>: Procedure name
Name of the WLanguage procedure run. This procedure is run in parallel with the application.
<Parameter 1>: Optional
Parameters that will be passed to the procedure. Caution: these parameters are passed by value (not by reference).
<Parameter N>: Optional
Parameters that will be passed to the procedure. Caution: these parameters are passed by value (not by reference).
Observaciones

Characteristics of a thread created in WLanguage

A thread created in WLanguage can only be a procedure or a class method. The thread cannot correspond to a WLanguage process (code of a control for example).
If the thread is a class method, ThreadExecute must be run from one of the processes of the class (constructor or method).

Thread and HFSQL

HFSQL contexts are automatically duplicated when ThreadExecute is executed: the number of HFSQL contexts is equal to the number of threads currently run. The entire HFSQL context is copied (filter, search condition, etc.). The HFSQL context evolves independently in each thread.
This allows you, for example, to perform two different iterations on the same data file in two different threads.
Two methods can be used to copy HFSQL contexts:
  • Full copy of context (by default)
  • Light copy of context.
For more details on how HFSQL contexts are copied and their limits (depending on the database used), see HFSQL context management.
Ejemplo:
  • Se crea un filtro en el archivo de datos Customer.
  • Se llama a ThreadExecute para crear el CTX2 thread.
  • En cada subproceso (principal y CTX2) se filtra el archivo de datos Customer. Si se desactiva el filtro en el subproceso principal, el filtro seguirá activo en el subproceso CTX2.
Casos especiales:
  • Gestión asistida de errores HFSQL: Si se utilizan varios subprocesos en los archivos de datos, se recomienda personalizar la gestión de errores HFSQL para que no se muestren las ventanas predeterminadas. Utilice la función HOnError para desactivar la gestión automática de errores o para redirigir la gestión de errores a un procedimiento personalizado (sin mostrar ventanas). Para obtener más información, consulte Gestión asistida de errores HFSQL.
  • Escritura y asignaciones en un subproceso: Si los valores se escriben o se asignan en un Thread, los demás Thread en funcionamiento no comparten esta información. Se pueden producir algunas inconsistencias.

Characteristics of WLanguage procedure

Caution: The calls to Info, Error, ... lock all the threads currently run.
Remark: The parameters passed to the procedure are passed by value and not by reference.

Lifecycle of a thread

The thread is automatically stopped at the end of the execution of the WLanguage procedure started by ThreadExecute.
The thread is also stopped in the following cases:
  • if ThreadExecute is called from the code of a window, the thread will be stopped when the window is closed.
  • if ThreadExecute is called from a global process (initialization, explicit call in the main context), the thread will be stopped when the application is terminated.
  • if ThreadExecute is called in a class method, the thread is stopped when the object is destroyed.
To force the execution of the thread in the main context, use the threadGlobalContext constant.
To force the thread to stop, use ThreadStop. This function can be used to stop a thread from the main thread.
Remark: Make sure that the threads are stopped (by ThreadState or ThreadWait) before closing the windows or destroying the objects.

Error management

A fatal error occurs in the following cases:
  • if the procedure does not exist.
  • if a thread with the same name is currently running.

Procesos no permitidos

Atención: Los siguientes procesos no se pueden ejecutar en los subprocesos:
Atención: Los elementos de la interfaz de usuario (ventanas, controles, etc.) no pueden ser manipulados en un Thread.secundario
Cuando un Thread secundario debe interactuar con el usuario o actualizar la UI, debe utilizar un Process iniciado desde el Thread principal. Este proceso puede corresponder a:
  • un procedimiento global del proyecto o un procedimiento local (de una ventana, etc.) llamado con la función ExecuteMainThread,
  • el evento "Solicitud para actualizar la visualización" de una ventana, ejecutado con la función RequestRefreshUI.
Clasificación Lógica de negocio / UI: Código neutro
Componente: wd290vm.dll
Versión mínima requerida
  • Versión 9
Esta página también está disponible para…
Comentarios
Video threadExecute
https://youtu.be/IThk-OAzffA

https://windevdesenvolvimento.blogspot.com/2019/01/dicas-1996-windev-threads-02.html
amarildo
24 01 2019

Última modificación: 28/03/2024

Señalar un error o enviar una sugerencia | Ayuda local