




已阅读5页,还剩12页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
附录AUnder the Windows platform, multi-threaded programmingA thread is a process execution path, it contains separate stack and CPU register 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 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 multi-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. Windows is a multitasking operating system, a process in Windows contains one or more threads. 32-bit Windows environment Win32 API provides 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 can be based on the needs and characteristics of the application select the appropriate tool. In order so that we can fully understand the Windows multi-threaded programming techniques, this article will focus on Win32 API and MFC are two ways of how to prepare multi-threaded programs. Multithreaded Programming in Win32 and MFC class 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 process 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 multi-threaded Win32 API programming: Win32 API is the Windows operating 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 provide multi-threading applications, Win32 API function provides some focus on procedures for handling multi-threaded set of functions. Directly with the Win32 API to program design has many advantages: Win32-based application code execution is small, high efficiency, but it requires programmers to write code more, and all systems need to manage the resources available to the program. Programming with the Win32 API directly on the Windows system 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 efficiency of the programmer. 1. With the Win32 function to create and terminate threads Win32 function 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 thread thread function is as follows: HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,DWORD dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,DWORD dwCreationFlags,LPDWORD lpThreadId); HANDLE CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes, DWORD dwStackSize, LPTHREAD_START_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 in dwCreationFlags CREATE_SUSPENDED property, then the thread is not immediately executed, but the first suspended, until the calls started after ResumeThread threads in the process can call the following function to set the priority of the thread: BOOL SetThreadPriority(HANDLE hThread,int nPriority); BOOL SetThreadPriority (HANDLE hThread, int nPriority); When the function returns 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 function: BOOL TerminateThread(HANDLE hThread,DWORD dwExitCode); 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 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 synchronization In the thread body, if the thread is completely independent data access with other threads and other resources 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 conflict is inevitable, in order to address this thread synchronization problems, Win32 API provides 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 objects access control should use this function. Win32 API provides 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 returned, the threads in a wait state, when the thread consumes very little CPU time. 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 dwMilliseconds); DWORD WaitForSingleObject (HANDLE hHandle, DWORD dwMilliseconds); The function can be used to simultaneously monitor multiple WaitForMultipleObject synchronization object, the function is declared as: DWORD WaitForMultipleObject(DWORD nCount,CONST HANDLE *lpHandles,BOOL bWaitAll,DWORD dwMilliseconds); DWORD WaitForMultipleObject (DWORD nCount, CONST HANDLE * lpHandles, BOOL bWaitAll, DWORD dwMilliseconds); (1) mutex object Mutex state of the object by any thread in that it does not have a time signal, it was a time when no signal. Mutex objects are suitable for coordination of multiple threads exclusive 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 function, 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 time 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 object Signal objects allow multiple threads simultaneously access shared resources in the 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, call ReleaseSemaphore function, the signal object counter plus one. Among them, the counter value is greater than or equal to 0, but less than or equal 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, call ReleaseSemaphore function will increase to its maximum value the counter, you 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. After access to shared resources should be occupied by the release of the signal objects: ReleaseSemaphore (); (3) the event object Event 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 occur, 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 with CreateEvent function. This function can be specified event object class and the initial state of the event. If the manual reset event, it always maintained a signal pick-like Ba Ban esetEvent function 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. SetEvent With SetEvent can set the event object to signaled. OpenEvent In the establishment of event, named for the object, so that other threads in the process can be used to open the specified function name OpenEvent event object handle. (4) exclusion zone object Asynchronous execution in the exclusion zone, it can only be in the same process of dealing with shared 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_SECTION used to define a structure of exclusion zone object is called before the process using the following function to initialize the object: VOID InitializeCriticalSection(LPCRITICAL_SECTION); VOID InitializeCriticalSection (LPCRITICAL_SECTION); When a thread uses the exclusion zone, call the function: EnterCriticalSection or TryEnterCriticalSection; When asked to take exit exclusion zone, call the function LeaveCriticalSection, the release of the exclusion zone occupied by the object for other threads. MFC-based multi-threaded programming: Microsofts VC + + MFC is to provide an integrated environment based library for programmers, it uses the class library to encapsulate Win32 API way to class provided to developers. Because of its fast, simple, powerful and so loved by the majority of developers. Therefore, it is recommended to use MFC class library application development. In VC + + with the MFC class library, provides support for multithreaded programming, basic principles and design based on the same Win32 API, but MFC synchronization 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 to receive user input, handle events, and message threads. 1. Worker thread Relatively 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 resources, 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,int nPriority= THREAD_PRIORITY_NORMAL,UINT nStackSize =0,DWORD dwCreateFlags=0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL); UINT ThreadFunction( LPVOID pParam) 。 CWinThread * AfxBeginThread (AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL); parameter pfnThreadProc is the thread of execution, function prototype is: UINT ThreadFunction (LPVOID pParam). Parameter is passed to the implementation of pParam argument; Parameter is the thread nPriority rights, optional values: HREAD_PRIORITY_NORMAL 、 THREAD_PRIORITY_LOWEST 、 THREAD_PRIORITY_HIGHEST 、 THREAD_PRIORITY_IDLE 。 THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_IDLE. Parameter dwCreateFlags is a sign of the thread is created, you can value CREATE_SUSPENDED, that thread is created in a suspended state, called ResumeThread thread continues to run after the function, or the value of 0 indicates a thread is created after running. CWinThread class object return value is a pointer, its member variables m_hThread for the thread handle, in the way of Win32 API functions 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 the Win32 API function pWinThread -m_Thread thread 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. The user interface thread MFC-based applications have an application object, which is CWinApp derived class 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. Class C W inApp derived from the C W inThread, C W inThread user interface thread is the basic class. We write the user interface thread, you need to derive from C W inThread thread of our own class, ClassWizard can help us do this work. First use ClassWizard to derive a new class, set the base class CwinThread. Note: The class DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE macros are necessary because you need to create threads dynamically created class object. Necessary initialization and exit code can be placed in the class, respectively, and ExitInstance function InitInstance. If you need to create a window, can be done in the InitInstance function. And then create a thread and start the thread. Two methods can be used to create the user interface thread, MFC provides two versions of the AfxBeginThread function, 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, call CWinThread: CreateThread function 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, the object is deleted before the end of the thread. CWinThread thread has completed the end of our work. 3. Thread Synchronization Earlier we introduced the Win32 API provides several objects related to thread synchronization in the MFC class library in a few objects in the class of this package, they have a common base class CSyncObject, their correspondence to: Semaphore corresponding CSemaphore, Mutex corresponding CMutex, Event corresponding CEvent, CriticalSection corresponding CCriticalSection. In addition, MFC functions of the two also had to wait for packages that CSingleLock and CMultiLock. Similar to the four objects for use in the example here to illustrate CMutex: Create a CMutex object: CMutex mutex(FALSE,NULL,NULL); CMutex mutex (FALSE, NULL, NULL); Or CMutex mutex; When each thread to access shared resources using the following code: CSingleLock sl(&mutex); CSingleLock sl (& mutex); sl.Lock (); if (sl.IsLocked () / / Operate on shared resources . sl.Unlock();Conclusion Here, draw attention to is that in multi-threaded programming to be especially careful when dealing with resource sharing and multi-threaded debugging problems. 附录BWindows平台下的多线程编程信息工程系2007级计算机科学与技术黎向阳译,李仲生指导线程是进程的一条执行路径,它包含独立的堆栈和CPU寄存器状态,每个线程共享所有的进程资源,包括打开的文件、信号标识及动态分配的内存等。一个进程内的所有线程使用同一个地址空间,而这些线程的执行由系统调度程序控制,调度程序决定哪个线程可执行以及什么时候执行线程。线程有优先级别,优先权较低的线程必须等到优先权较高的线程执行完后再执行。在多处理器的机器上,调度程序可将多个线程放到不同的处理器上去运行,这样可使处理器任务平衡,并提高系统的运行效率。 Windows是一种多任务的操作系统,在Windows的一个进程内包含一个或多个线程。32位Windows环境下的Win32 API提供了多线程应用程序开发所需要的接口函数,而利用中提供的标准库也可以开发多线程应用程序,相应的类库封装了多线程编程的类,用户在开发时可根据应用程序的需要和特点选择相应的工具。为了使大家能全面地了解Windows多线程编程技术,本文将重点介绍Win32 API和MFC两种方式下如何编制多线程程序。 多线程编程在Win32方式下和MFC类库支持下的原理是一致的,进程的主线程在任何需要的时候都可以创建新的线程。当线程执行完后,自动终止线程; 当进程结束后,所有的线程都终止。所有活动的线程共享进程的资源,因此,在编程时需要考虑在多个线程访问同一资源时产生冲突的问题。当一个线程正在访问某进程对象,而另一个线程要改变该对象,就可能会产生错误的结果,编程时要解决这个冲突。Win32 API下的多线程编程:Win32 API是Windows操作系统内核与应用程序之间的界面,它将内核提供的功能进行函数包装,应用程序通过调用相关函数而获得相应的系统功能。为了向应用程序提供多线程功能,Win32 API函数集中提供了一些处理多线程程序的函数集。直接用Win32 API进行程序设计具有很多优点: 基于Win32的应用程序执行代码小,运行效率高,但是它要求程序员编写的代码较多,且需要管理所有系统提供给程序的资源。用Win32 API直接编写程序要求程序员对Windows系统内核有一定的了解,会占用程序员很多时间对系统资源进行管理,因而程序员的工作效率降低。1. 用Win32函数创建和终止线程 Win32函数库中提供了操作多线程的函数,包括创建线程、终止线程、建立互斥区等。在应用程序的主线程或者其他活动线程中创建新的线程的函数如下: HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes,DWORD dwStackSize,LPTHREAD_START_ROUTINE lpStartAddress,LPVOID lpParameter,DWORDdwCreationFlags,LPDWORD lpThreadId); 如果创建成功则返回线程的句柄,否则返回NULL。创建了新的线程后,该线程就开始启动执行了。但如果在dwCreationFlags中使用了CREATE_SUSPENDED特性,那么线程并不马上执行,而是先挂起,等到调用ResumeThread后才开始启动线程,在这个过程中可以调用下面
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论