![]() |
| Home |
|
|
Function RTKSetTaskSwitchHookRTKernel-32 can call a user-defined function in every task switch. Such a task switch hook is installed using function RTKSetTaskSwitchHook:
typedef void (__cdecl * RTKTaskSwitchHook)(RTKTaskHandle OldTask,
RTKTaskHandle NewTask);
void RTKSetTaskSwitchHook(RTKTaskSwitchHook Hook,
RTKTaskSwitchHook * OldHook);
ParametersHookA function with two task handles as parameters, respectively referencing the task being suspended and the task being activated. OldHookShould point to a variable to receive a pointer to the previously installed hook. For an application task switch hook, some important restrictions apply. Specifically, it must be considered that:
If any of these restrictions is violated, the program will very probably crash. Possible error messages may be misleading. If Win32 emulation is used, all TLS-related functions will access OldTask's data. Using a task switch hook is discouraged. In particular, it should not be attempted to solve reentrance problems by using a hook; resource semaphores are much better suited for this purpose. It should also be noted that a task switch hook can severly degrade RTKernel-32's performance. The following example shows how the number of task switches can be counted for each task using a task switch hook:
#include <stdlib.h>
#include <stdio.h>
#include <rtk32.h>
int UserDataIndex;
RTKTaskSwitchHook OldHook;
void RTKAPI MyThread(void * p)
{
while (1)
RTKDelay((RTKDuration)p);
}
void RTKAPI TheHook(RTKTaskHandle Old, RTKTaskHandle New)
{
int Count;
Count = (int) RTKGetUserData(New, UserDataIndex);
Count++;
RTKSetUserData(New, UserDataIndex, (void*) Count);
OldHook(Old, New);
}
int main(void)
{
RTKTaskHandle H1, H2;
RTKernelInit(3);
UserDataIndex = RTKAllocUserData();
RTKSetTaskSwitchHook(TheHook, &OldHook);
H1 = RTKCreateThread(MyThread, 2, 1024, 0, (void*)1, "ThreadA");
H2 = RTKCreateThread(MyThread, 2, 1024, 0, (void*)3, "ThreadB");
RTKDelay(20);
printf("Task switches for ThreadA: %i, ThreadB: %i\n",
RTKGetUserData(H1, UserDataIndex),
RTKGetUserData(H2, UserDataIndex));
return 0;
}
|