收藏 分销(赏)

Windows平台下的多线程编程(计算机论文翻译).doc

上传人:二*** 文档编号:4514750 上传时间:2024-09-26 格式:DOC 页数:17 大小:73KB
下载 相关 举报
Windows平台下的多线程编程(计算机论文翻译).doc_第1页
第1页 / 共17页
亲,该文档总共17页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

1、附录AUnder theWindowsplatform, multi-threaded programmingA thread is a process execution path, it contains separate stack andCPUregister state, the process of each thread to share all resources, including open files, signal identification and dynamic allocation of memory and so on.All threads within a

2、 process using the same address space, and these threads of execution by the system scheduler control thread scheduler to decide which and when to execute the executable threads.Thread has priority, lower priority thread must wait until the higher priority thread after their implementation.In the mu

3、lti-processor machines, the scheduler can be multiple threads running up into different processors, it will give the processor the task balance, and improve efficiency of the system.Windowsis a multitasking operating system, a process inWindowscontains one or more threads.32-bit WindowsenvironmentWi

4、n32 APIprovides a multi-threaded application development interface functions required, and use of VC in the standard C libraries are also provided to develop multithreaded applications, the corresponding MFC class library encapsulates the class of multi-threaded programming users in the development

5、can be based on the needs and characteristics of the application select the appropriate tool.In order so that we can fully understand theWindowsmulti-threaded programming techniques, this article will focus onWin32 APIandMFCare two ways of how to prepare multi-threaded programs.Multithreaded Program

6、ming inWin32andMFCclass library under way to support the principle is the same, the main thread of the process at any time needed to create a new thread.When the thread has finished, automatically terminate the thread; when the process is complete, all threads are terminated.Threads share the proces

7、s of all activities of resources, therefore, be considered when programming multiple threads access the same resource conflict problem.When a thread is accessing a process object, and another thread to change the object, it may produce incorrect results, programming to solve this conflict.Under the

8、multi-threadedWin32 APIprogramming:Win32 APIis theWindowsoperating system kernel and the interface between applications, which will provide the functions of the kernel function wrapper, the application obtained by calling the correlation function of the corresponding system function.In order to prov

9、ide multi-threading applications,Win32 APIfunction provides some focus on procedures for handling multi-threaded set of functions.Directly with theWin32 APIto program design has many advantages: Win32-based application code execution is small, high efficiency, but it requires programmers to write co

10、de more, and all systems need to manage the resources available to the program.Programming with theWin32 APIdirectly on theWindowssystem kernel programmer is required to have a certain understanding, it will take a lot of time on the programmer to manage system resources, thus reducing the efficienc

11、y of the programmer.1.With theWin32function to create and terminate threadsWin32function library provides a function of multi-threaded operation, including creating threads, terminate threads, the establishment of exclusive zones.In the applications main thread or other activities to create a new th

12、read thread function is as follows:HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,DWORDdwStackSize,LPTHREAD_START_ROUTINElpStartAddress,LPVOIDlpParameter,DWORDdwCreationFlags,LPDWORDlpThreadId);HANDLE CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, DWORD dwStackSize, LPTHREAD_S

13、TART_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId);If you create a successful thread handle is returned, otherwise NULL.Create a new thread, the thread started to execute.However, if used indwCreationFlags CREATE_SUSPENDEDproperty, then the thread is not imme

14、diately executed, but the first suspended, until the calls started afterResumeThreadthreads in the process can call the following function to set the priority of the thread:BOOL SetThreadPriority(HANDLE hThread,intnPriority);BOOL SetThreadPriority (HANDLE hThread, intnPriority);When the function ret

15、urns the calling thread, the thread automatically terminates.If you need to terminate during the execution of the thread can call the function:VOID ExitThread(DWORD dwExitCode);VOID ExitThread (DWORD dwExitCode);If you terminate a thread in the thread on the outside, you can call the following funct

16、ion:BOOL TerminateThread(HANDLE hThread,DWORDdwExitCode);BOOL TerminateThread (HANDLE hThread, DWORD dwExitCode);It should be noted: this function may cause system instability, and the thread does not release the occupied resources.Therefore, under normal circumstances, it is recommended not to use

17、this function.If you want to terminate the thread is the last thread within the process, the thread is terminated after the corresponding process should be terminated.2.Thread synchronizationIn the thread body, if the thread is completely independent data access with other threads and other resource

18、s without conflict operation, the method can be carried out in accordance with generally single-threaded programming.However, the situation in multi-threaded processing is often not the case, often between threads simultaneously access some resources.Because access to shared resources causes conflic

19、t is inevitable, in order to address this thread synchronization problems,Win32 APIprovides a variety of synchronization objects to help programmers access to shared resources to resolve the conflict.In presenting these synchronization objects introduce wait functions before, because all the control

20、 objects access control should use this function.Win32 APIprovides a set of threads can block waiting for the implementation of its own function.These functions in its argument object generates one or more synchronization signal, or exceeds the waiting time will be returned.Waiting function is not r

21、eturned, the threads in a wait state, when the thread consumes very littleCPUtime.Not only can guarantee the wait function using thread synchronization, but also can improve the running efficiency.Waiting function is the most commonly used:DWORD WaitForSingleObject(HANDLE hHandle,DWORD dwMillisecond

22、s);DWORD WaitForSingleObject (HANDLE hHandle, DWORD dwMilliseconds);The function can be used to simultaneously monitor multipleWaitForMultipleObjectsynchronization object, the function is declared as:DWORD WaitForMultipleObject(DWORD nCount,CONST HANDLE *lpHandles,BOOLbWaitAll,DWORDdwMilliseconds);D

23、WORD WaitForMultipleObject (DWORD nCount, CONST HANDLE * lpHandles, BOOL bWaitAll, DWORD dwMilliseconds);(1)mutex objectMutexstate of the object by any thread in that it does not have a time signal, it was a time when no signal.Mutexobjects are suitable for coordination of multiple threads exclusive

24、 access to shared resources.The following steps can use the object:First, create a mutex object, get the handle:HANDLE CreateMutex();HANDLE CreateMutex ();Then, in the thread before the possible areas of conflict (ie, before access to shared resources) calls WaitForSingleObject, the handle to the fu

25、nction, the request takes mutex object:dwWaitResult = WaitForSingleObject(hMutex,5000L);dwWaitResult = WaitForSingleObject (hMutex, 5000L);Shared resources conclusion of the visit, the release of the occupation of the mutex object:ReleaseMutex(hMutex);ReleaseMutex (hMutex);Mutex object at the same t

26、ime can only be occupied by a thread, when the mutex object is occupied by a thread when another thread would like to take it if you must wait until after the release of the previous thread to succeed.(2)signal objectSignal objects allow multiple threads simultaneously access shared resources in the

27、 creation of object may also specify the maximum number of threads access.When a thread successfully apply for access to the signal by a counter object, callReleaseSemaphorefunction, the signal object counter plus one.Among them, the counter value is greater than or equal to 0, but less than or equa

28、l to the maximum specified when created.If an application to create a signal object, the initial value of its counter is set to 0 to block the other thread to protect the resources.And other initialization is complete, callReleaseSemaphorefunction will increase to its maximum value the counter, you

29、can access a normal visit.The following steps can use the object:First, create the signal object:HANDLE CreateSemaphore();HANDLE CreateSemaphore ();A signal or open object:HANDLE OpenSemaphore();HANDLE OpenSemaphore ();Then, access to shared resources in the thread before calling WaitForSingleObject

30、.After access to shared resources should be occupied by the release of the signal objects:ReleaseSemaphore ();(3) the event objectEvent object(Event)is the simplest synchronization objects, which includes both signal and no signal state.Threads access a resource, you need to wait for some event to o

31、ccur, then the most appropriate to use the event object.For example: only the data received in the communication port buffer, the monitor thread is activated.The event object is created withCreateEventfunction.This function can be specified event object class and the initial state of the event.If th

32、e manual reset event, it always maintained a signal pick-likeBa BanesetEventfunction reset to no signal events.If the event is automatically reset, then its state after the release of a single waiting thread will automatically become free signal.SetEventWithSetEventcan set the event object to signal

33、ed.OpenEventIn the establishment of event, named for the object, so that other threads in the process can be used to open the specified function nameOpenEventevent object handle.(4)exclusion zone objectAsynchronous execution in the exclusion zone, it can only be in the same process of dealing with s

34、hared resources between threads.At a time when several methods described above can be used, however, the use of exclusion zones approach makes more efficient synchronization management.CRITICAL_SECTIONused to define a structure of exclusion zone object is called before the process using the followin

35、g function to initialize the object:VOID InitializeCriticalSection(LPCRITICAL_SECTION);VOID InitializeCriticalSection (LPCRITICAL_SECTION);When a thread uses the exclusion zone, call the function:EnterCriticalSectionorTryEnterCriticalSection;When asked to take exit exclusion zone, call the function

36、LeaveCriticalSection, the release of the exclusion zone occupied by the object for other threads.MFC-based multi-threaded programming:Microsofts VC+ + MFCis to provide an integrated environment based library for programmers, it uses the class library to encapsulateWin32 APIway to class provided to d

37、evelopers.Because of its fast, simple, powerful and so loved by the majority of developers.Therefore, it is recommended to useMFCclass library application development.InVC + +with theMFCclass library, provides support for multithreaded programming, basic principles and design based on the sameWin32A

38、PI, butMFCsynchronization objects on a wrapper, so to achieve more convenient to avoid the object handle management the tedious work.In MFC, the thread is divided into two types: worker threads and user interface thread.Work earlier in the thread with the same thread, the thread is a user interface

39、to receive user input, handle events, and message threads.1.Worker threadRelatively simple work-thread programming, design ideas and the mentioned earlier the same: a basic function represents a thread, create and start the thread, the thread into the running state; if the thread is used to share re

40、sources, the need for resource synchronization.In this way create a thread and start the thread can call the function:CWinThread*AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam,intnPriority= THREAD_PRIORITY_NORMAL,UINT nStackSize =0,DWORD dwCreateFlags=0, LPSECURITY_ATTRIBUTES lpSecurity

41、Attrs = NULL);UINT ThreadFunction( LPVOID pParam)。CWinThread * AfxBeginThread (AFX_THREADPROC pfnThreadProc, LPVOID pParam, intnPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL);parameterpfnThreadProcis the thread of execut

42、ion, function prototype is:UINT ThreadFunction (LPVOID pParam).Parameter is passed to the implementation ofpParamargument;Parameter is the threadnPriorityrights, optional values:HREAD_PRIORITY_NORMAL、THREAD_PRIORITY_LOWEST、THREAD_PRIORITY_HIGHEST、THREAD_PRIORITY_IDLE。THREAD_PRIORITY_NORMAL, THREAD_P

43、RIORITY_LOWEST, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_IDLE.ParameterdwCreateFlagsis a sign of the thread is created, you can value CREATE_SUSPENDED, that thread is created in a suspended state, calledResumeThreadthread continues to run after the function, or the value of 0indicatesa thread is cre

44、ated after running.CWinThreadclass object return value is a pointer, its member variablesm_hThreadfor the thread handle, in the way ofWin32 APIfunctions that operate under the parameters of the thread are required to provide a handle to the thread, so when the thread is created you can use all theWi

45、n32 APIfunctionpWinThread -m_Threadthread related operations.Note: If a class object to create and start the thread, the thread function should be defined as global functions outside the class.2. Theuser interface threadMFC-based applications have an application object, which isCWinAppderived class

46、object that represents the application process, the main thread.When the thread and exit the thread is executed, because no other threads in the process, the process ends automatically.ClassCWinApp derived from theCWinThread,CWinThread user interface thread is the basic class.We write the user inter

47、face thread, you need to derive fromCWinThread thread of our own class,ClassWizardcan help us do this work.First useClassWizardto derive a new class, set the base class CwinThread.Note: The classDECLARE_DYNCREATEandIMPLEMENT_DYNCREATEmacros are necessary because you need to create threads dynamicall

48、y created class object.Necessary initialization and exit code can be placed in the class, respectively, andExitInstancefunction InitInstance.If you need to create a window, can be done in theInitInstancefunction.And then create a thread and start the thread.Two methods can be used to create the user

49、 interface thread,MFCprovides two versions of theAfxBeginThreadfunction, one used to create the user interface thread.The second method is divided into two steps: first, the calling thread class constructor creates a thread object; Second, callCWinThread:CreateThreadfunction to create the thread.After the establishment and start the thread, the thread function in the process of implementation has been effective.If the thread object,

展开阅读全文
相似文档                                   自信AI助手自信AI助手
猜你喜欢                                   自信AI导航自信AI导航
搜索标签

当前位置:首页 > 学术论文 > 其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        获赠5币

©2010-2024 宁波自信网络信息技术有限公司  版权所有

客服电话:4008-655-100  投诉/维权电话:4009-655-100

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :gzh.png    weibo.png    LOFTER.png 

客服