Asynchronous procedures
>> Wednesday, October 14, 2009
You may want to implement a system with threads and asynchronous calling of procedures. Here's the tip.
Asynchronous procedures are procedures executed in context of a thread.
Each thread has two queues of asynchronous procedures: a queue for user and a queue for system.
It means that you can push function pointers into user queue.
The first thing to do is determine the procedure (function ). It has prototype (PAPFUNC) :
VOID CALLBACK function_name(DWORD dwData);
Next, use the function QueueUserAPC to determine the thread, into its queue we put the asynchronous functions. It has prototype:
DWORD QueueUserAPC(PAPCFUNC pfnAPC, HANDLE hThread, DWORD dwData);
That is all. Here 's the sample code:
#include
#incude
HANDLE hThread;
DWORD idThread;
DWORD dwRet;
void CALLBACK a_proc(DWORD p)
{
int n;
DWORD *ptr = (DWORD *)p;
cout << "Input integer: ";cin >> n;
*ptr += n;
}
DWORD WINAPI add(LPVOID ptr)
{
cout << "Initial count: " << *(DWORD*)ptr << endl;// -> now wait for completion of asynchronous procedure
SleepEx(INFINITE, TRUE);
cout << "Final count = " << *(DWORD*)ptr << endl;return 0;}int main(){DWORD count = 10;hThread = CreateThread(NULL, 0, add, &count, 0, &idThread);Sleep(1000);dwRet = QueueUserAPC(a_proc, hThread, (DWORD)&count);WaitForSingleObject(hThread, INFINITE);CloseHandle(hThread);return 0;}
0 comments:
Post a Comment