ICZelion TUT15

zhaozj2021-02-11  201

Tutorial 15: Multithreading Programming

.........

Download The Example Here.

Theory: In previous tutorial, you learn the a process consists of at least one thread:. The primary thread A thread is a chain of execution You can also create additional threads in your program You can view multithreading as multitasking within one program... In term of implementation, a thread is a function that runs concurrently with the main program. you can run several instances of the same function or you can run several functions simultaneously depending on your requirement. Multithreading is specific to Win32, no Win16 counterpart exists.

Threads run in the same process so they can access any resources in the process such as global variables, handles etc. However, each thread has its own stack so local variables in each thread are private. Each thread also owns its private register set so when Windows Switches To Other Threads, The Thread CAN "Remember" ITS Last Status and Can Resume "The Task When It Gains Control Again. This is handled intenally by Windows.

We can Divide Threads INTO TWO CATERORIES:

User interface thread:. This type of thread creates its own window so it receives windows messages It can respond to the user via its own window hence the name This type of thread is subject to Win16 Mutex rule which allows only one user interface thread in. 16-bit user and gdi kernel. While a user interface thread is executing code in 16-bit user and gdi kernel, other UI threads can not use the service of the 16-bit user and gdi kernel. Note that this Win16 Mutex is specific to Windows 95 since underneath, Windows 95 API functions thunk down to 16-bit code Windows NT has no Win16 Mutex so the user interface threads under NT work more smoothly than under Windows 95. Worker thread:. This type of thread does not create a window so it can not receive any windows message It exists primarily to do the assigned job in the background hence the name worker thread I advise the following strategy when using multithreading capability of Win32:.. Let the primary thread do user interface stuff and th e other threads do the hard work in the background. In this way, the primary thread is like a Governor, other threads are like the Governor's staff. The Governor delegates jobs to his staff while he maintains contact with the public. The Governor staff obediently performs the work and reports back to the Governor. If the Governor were to perform every task himself, he would not be able to give much attention to the public or the press. That's akin to a window which is busy doing a lengthy job in its primary thread: it does not respond to the user until the job is completed Such a program can benefit from creating an additonal thread which is responsible for the lengthy job, allowing the primary thread to respond to the user '.

S Commands.We CAN CREATE A THREAD BY CALLING CREATETHREAD FUNCTION Which Has The FOLLOWING SYNTAX:

Createthread Proto LPTHREADATTRIBUTES: DWORD, / DWSTACKSIZE: DWORD, / LPSTARTDRESS: DWORD, / LPPARATER: DWORD, / DWCREATIONFLAS: DWORD, / LPTHREADID: DWORD

. CreateThread function looks a lot like CreateProcess lpThreadAttributes -> You can use NULL if you want the thread to have default security descriptor dwStackSize -..> Specify the stack size of the thread If you want the thread to have the same stack size . as the primary thread, use NULL as this parameter lpStartAddress -.> Address of the thread function.It's the function that will perform the work of the thread This function MUST receive one and only one 32-bit parameter and return a 32- . bit value lpParameter -> The parameter you want to pass to the thread function dwCreationFlags -.> 0 means the thread runs immediately after it's created The opposite is CREATE_SUSPENDED flag lpThreadId -..> CreateThread function will fill the thread ID of The Newly Created Thread at this address.

If CreateThread call is sucessful, it returns the handle of the newly created thread. Otherwise, it returns NULL. The thread function runs as soon as CreateThread call is success ful unless you specify CREATE_SUSPENDED flag in dwCreationFlags. In that case, the thread is suspended until ResumeThread function is called. When the thread function returns with ret instruction, Windows calls ExitThread function for the thread function implicitly. You can call ExitThread function with in your thread function yourself but there 's little point in doing so. You can retrieve the exit code of a thread by calling GetExitCodeThread function. If you want to terminate a thread from other thread, you can call TerminateThread function. But you should use this function under extreme circumstance since this function terminates the thread immediately without giving the thread any chance to Clean Up after Itself.now Let's Move To The Communication Methods Between Threads. There Are Three of Them:

Using global variables Windows messages Event Threads share the process's resources including global variables so the threads can use global varibles to communicate with each other. However this method must be used with care. Thread synchronization must enter into consideration. For example, if two threads use the same structure of 10 members, what happens when Windows suddenly yanks the control from one of the thread when it was in the middle of updating the structure? The other thread will be left with an inconsistent data in the structure! Do not make any Mistake, Multithreading Programs Are Harden. This Sort of bug seems to happen at random Which is very hard to track down.

You can also use Windows messages to communicate between threads If the threads are all user interface ones, there's no problem:.. This method can be used as a two-way communication All you have to do is defining one or more custom windows messages that Are Meaningful to The Threads. You Define a Custom Message by Using WM_USER Message As The Base Value Say, You CAN Define It Like this: WM_MYCUSTOMMSG EQU WM_USER 100H

Windows will not use any value from WM_USER upward for its own messages so you can use the value WM_USER and above as your own custom message value. If one of the thread is a user interface thread and the other is a worker one, you can not use This Method As Two-Way Communication Since A Worker Thread Doesn't Have ITS OWN Window So It Doesn't Have A Message Queue. You can Use the Following Scheme:

User Interface Thread ------> Global Variable (s) ----> Worker Thread Worker Thread ------> Custom WINDOW Message (s) ----> User Interface Thread

In fact, we will use this method in our example. The last communication method is an event object. You can view an event object as a kind of flag. If the event object is in "unsignalled" state, the thread is dormant or sleeping , In this State, The Thread Doesn't Receive CPU Time Slice. When the Event Object Is in "Signalled" State, Windows "Wakes Up" The Thread and It Starts Performing The Assigned Task.

Example: You should download the example zip file and run thread1.exe Click the "Savage Calculation" menu item This will instruct the program to perform "add eax, eax" for 600,000,000 times Note that during that time, you can not do... anything with the main window: you can not move it, you can not activate its menu, etc. When the calculation is completed, a message box appears After that the window accepts your command normally.To avoid this type of inconveniece to the user, we. can move the "calculation" routine into a separate worker thread and let the primary thread continue with its user interface task. You can see that even though the main window responds more slowly than usual, it still responds

.386 .model flat, stdcall option casemap: none WinMain proto: DWORD,: DWORD,: DWORD,: DWORD include /masm32/include/windows.inc include /masm32/include/user32.inc include / masm32 / include / kernel32. Inc includelib /masm32/lib/user32.lib incruDelib /masm32/lib/kernel32.lib

.const idm_create_thread EQU 1 IDM_EXIT EQU 2 WM_FINISH EQU WM_USER 100H

.DATA CLASSNAME DB "WIN32ASMTHREADCLASS", 0 AppName DB "Win32 ASM Multithreading Example", 0 Menuname DB "Firstmenu", 0 SuccessString DB "The Calculation IS Completed!", 0

.data? hinstance hinstance? CommandLine LPSTR? HWND HANDLE? Threadid DWORD?

. Code Start: Invoke GetModuleHandle, Null Mov Hinstance, Eax Invoke Getcommandline Mov Commandline, Eax Invoke Winmain, Hinstance, Null, CommandLine, SW_SHOWDEFAULT INVOKE EXITPROCESS, EAX

WinMain proc hInst: HINSTANCE, hPrevInst: HINSTANCE, CmdLine: LPSTR, CmdShow: DWORD LOCAL wc: WNDCLASSEX LOCAL msg: MSG mov wc.cbSize, SIZEOF WNDCLASSEX mov wc.style, CS_HREDRAW or CS_VREDRAW mov wc.lpfnWndProc, OFFSET WndProc mov wc. cbClsExtra, NULL mov wc.cbWndExtra, NULL push hInst pop wc.hInstance mov wc.hbrBackground, COLOR_WINDOW 1 mov wc.lpszMenuName, OFFSET MenuName mov wc.lpszClassName, OFFSET ClassName invoke LoadIcon, NULL, IDI_APPLICATION mov wc.hIcon, eax mov wc.hIconSm, eax invoke LoadCursor, NULL, IDC_ARROW mov wc.hCursor, eax invoke RegisterClassEx, addr wc invoke CreateWindowEx, WS_EX_CLIENTEDGE, aDDR ClassName, aDDR AppName, / WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, / CW_USEDEFAULT, 300,200, NULL, NULL, / hInst, Null Mov Hwnd, Eax Invoke ShowWindow, Hwnd, SW_SHOWNORMAL INVOKE UPDATEWINDOW, HWND .WHILE TRUE INVOKE GETMESSAGE, ADDR MSG, NULL, 0, 0 .Break .if (! EAX) Invoke TranslateMessage, Addr Msg Invoke DispatchMessage, Addr Msg .Endw Mov Eax, Msg.wParam Ret Winmain Endp

WndProc proc hWnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM .IF uMsg == WM_DESTROY invoke PostQuitMessage, NULL .ELSEIF uMsg == WM_COMMAND mov eax, wParam .if lParam == 0 .if ax == IDM_CREATE_THREAD mov eax, OFFSET ThreadProc invoke CreateThread, NULL, NULL, eax, / 0, / ADDR ThreadID invoke CloseHandle, eax .else invoke DestroyWindow, hWnd .endif .endif .ELSEIF uMsg == WM_FINISH invoke MessageBox, NULL, ADDR SuccessString, ADDR AppName, MB_OK .ELSE invoke DefWindowProc, hWnd, uMsg, wParam, lParam ret .ENDIF xor eax, eax ret WndProc endpThreadProc PROC USES ecx Param: DWORD mov ecx, 600000000 Loop1: add eax, eax dec ecx jz get_out jmp Loop1 get_out: invoke PostMessage, HWND, WM_FINISH, NULL, NULL RET ThreadProc ENDP

End Start

Analysis: The Main Program Presents The User with a Normal window with a menu. If The user selects "Create Thread" MENU Item, The Program Creates A Thread As Below:

.if ax == IDM_CREATE_THREAD mov eax, OFFSET ThreadProc invoke CreateThread, NULL, NULL, eax, / NULL, 0, / ADDR ThreadID invoke CloseHandle, eax The above function creates a thread that will run a procedure named ThreadProc concurrently with the primary thread . After the successful call, CreateThread returns immediately and ThreadProc begins to run. Since we do not use thread handle, we should close it else there'll be some leakage of memory. Note that closing the thread handle does not terminate the thread. Its only effect is that we can not use the thread handle anymore.ThreadProc PROC USES ecx Param: DWORD mov ecx, 600000000 Loop1: add eax, eax dec ecx jz get_out jmp Loop1 get_out: invoke PostMessage, hwnd, WM_FINISH, NULL, NULL ret ThreadProc ENDP

As you can see, Threadproc Performs a savage calculation Which Takes Quite a While to Finish and When IT Finishs It Posts A WM_FINISH Message To The Main Window. WM_FINISH IS Our Custom Message Defined Like this:

WM_FINISH EQU WM_USER 100H

You don't have to add wm_user with 100h But it's safer to do so.

THE WM_FINISH Message Is Meaningful Only With Our Program. When The Main Window Receives The WM_FINISH MESSAGE, IT RESPONS by Displaying a Message Box Saying That The Calculation IS Completed.

You Create Several Threads in succession by Several Times.

In this example, the communication is one-way in that only the thread can notify the main window If you want the main thread to send commands to the worker thread, you can so as follows:. Add a menu item saying something like "Kill Thread "in the menu a global variable which is used as a command flag. TRUE = Stop the thread, FALSE = continue the thread Modify ThreadProc to check the value of the command flag in the loop. When the user selects" Kill Thread "menu Item, The Main Program Will Set The Value True in The Command Flag. When Threadproc See That The Value of The Command Flag Is True, IT EXITS The loop and return.

转载请注明原文地址:https://www.9cbs.com/read-4668.html

New Post(0)