Presentation is loading. Please wait.

Presentation is loading. Please wait.

Threads and Thread Synchronization. Introduction In windows the basic unit of execution is the thread. It is the smallest schedulable unit of execution.

Similar presentations


Presentation on theme: "Threads and Thread Synchronization. Introduction In windows the basic unit of execution is the thread. It is the smallest schedulable unit of execution."— Presentation transcript:

1 Threads and Thread Synchronization

2 Introduction In windows the basic unit of execution is the thread. It is the smallest schedulable unit of execution. A Process is simply a container for threads.A Process is simply a container for threads. Each process has at least one thread.Each process has at least one thread. Threads are confined to context of the process that created them.Threads are confined to context of the process that created them. A thread executes code and manipulates data within its process’s address space. A thread executes code and manipulates data within its process’s address space. If two or more threads run in the context of a single process they share a common address space. They can execute the same code and manipulate the same data. If two or more threads run in the context of a single process they share a common address space. They can execute the same code and manipulate the same data.

3 A Thread Continues To Run Until The thread exceeds its quantum. The thread exceeds its quantum. A higher-priority thread becomes run able. A higher-priority thread becomes run able. The running thread yields by waiting for an event or object. The running thread yields by waiting for an event or object. When a thread is prevented from running because its priority is lower than other threads in the system, it is said to be ? Starved When a thread is prevented from running because its priority is lower than other threads in the system, it is said to be ? Starved

4 Types of Threads User Interface thread User Interface thread A worker thread A worker thread

5 Worker Thread These threads simply go on & on without interfacing with the user. These threads simply go on & on without interfacing with the user. A worker thread often terminates once its work is done. A worker thread often terminates once its work is done. background calculations background calculations background printing background printing

6 CWinThread* AfxBeginThread ( AFX_THREADPROC pfnThreadProc, LPVOID pParam, AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); ); Starting the Thread

7 pfnThreadProc: Pointer to the function that will run inside the thread. pfnThreadProc: Pointer to the function that will run inside the thread. LPVOID pParam: Parameter to be passed to the controlling function LPVOID pParam: Parameter to be passed to the controlling function nPriority: The desired priority of the thread. nPriority: The desired priority of the thread. nStackSize: Specifies the size in bytes of the stack for the new thread. nStackSize: Specifies the size in bytes of the stack for the new thread. dwCreateFlags: Additional flag that controls the creation of the thread. dwCreateFlags: Additional flag that controls the creation of the thread. lpSecurityAttrs: Specifies the security attributes for the thread. lpSecurityAttrs: Specifies the security attributes for the thread. Return Value: Pointer to the newly created thread object. Return Value: Pointer to the newly created thread object.

8 Each thread in Windows can be given a priority from 1 to 31 (with 31 being the highest priority). Each thread in Windows can be given a priority from 1 to 31 (with 31 being the highest priority). THREAD_PRIORITY_LOWEST-2 (subtracts 2 from current priority) THREAD_PRIORITY_BELOW_NORMAL-1 THREAD_PRIORITY_NORMAL 0 THREAD_PRIORITY_ABOVE_NORMAL+1 THREAD_PRIORITY_HIGHEST+2 For example, if a thread’s priority is changed by calling: SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL ), then its priority will become 8 (i.e., 9-1).

9 dwCreateFlags This flag can contain one of two values: This flag can contain one of two values: CREATE_SUSPENDED CREATE_SUSPENDED to create a thread that is suspended upon creation to create a thread that is suspended upon creation CWinThread::ResumeThread to start the thread running. CWinThread::ResumeThread to start the thread running. 0 Start the thread immediately after creation. 0 Start the thread immediately after creation.

10 Implementing a Thread Function UINT MyThreadProc(LPVOID pParam); UINT MyThreadProc(LPVOID pParam); As function stops executing, its stack and other resources are As function stops executing, its stack and other resources are deallocated, deallocated, and the CWinThread object is deleted. and the CWinThread object is deleted.

11 Terminating a thread A worker thread ends when the thread function executes a return statement or when any function anywhere in the thread calls AfxEndThread. A UI thread terminates when a WM_QUIT message is posted to its message queue or when the thread itself calls AfxEndThread. A thread can post a WM_QUIT message to itself with the API function ::PostQuitMessage. AfxEndThread, ::PostQuitMessage, and return all accept a 32-bit exit code that can be retrieved with ::GetExitCodeThread after the thread has terminated. The following statement copies the exit code of the thread referenced by pThread to dwExitCode: A worker thread ends when the thread function executes a return statement or when any function anywhere in the thread calls AfxEndThread. A UI thread terminates when a WM_QUIT message is posted to its message queue or when the thread itself calls AfxEndThread. A thread can post a WM_QUIT message to itself with the API function ::PostQuitMessage. AfxEndThread, ::PostQuitMessage, and return all accept a 32-bit exit code that can be retrieved with ::GetExitCodeThread after the thread has terminated. The following statement copies the exit code of the thread referenced by pThread to dwExitCode: DWORD dwExitCode; ::GetExitCodeThread (pThread->m_hThread, &dwExitCode); DWORD dwExitCode; ::GetExitCodeThread (pThread->m_hThread, &dwExitCode); If called for a thread that's still executing, ::GetExitCodeThread sets dwExitCode equal to STILL_ACTIVE (0x103). In this example, the thread handle passed to ::GetExitCodeThread is retrieved from the m_hThread data member of the CWinThread object encapsulating the thread. Anytime you have a CWinThread and you want to call an API function that requires a thread handle, you can get that handle from m_hThread. If called for a thread that's still executing, ::GetExitCodeThread sets dwExitCode equal to STILL_ACTIVE (0x103). In this example, the thread handle passed to ::GetExitCodeThread is retrieved from the m_hThread data member of the CWinThread object encapsulating the thread. Anytime you have a CWinThread and you want to call an API function that requires a thread handle, you can get that handle from m_hThread. Return from the thread function. Return from the thread function. 0 is a successful return and 1 is a failure. 0 is a successful return and 1 is a failure. void AfxEndThread( UINT status ); void AfxEndThread( UINT status );

12 Suspending and Resuming a Thread A thread may be suspended or put in a dormant state by a call to the SuspendThread function. A thread may be suspended or put in a dormant state by a call to the SuspendThread function. The threads execution may be resumed with a call to the Resume thread function. The threads execution may be resumed with a call to the Resume thread function.

13 Demo Worker Thread

14 User Interface thread User Interface (UI) threads create windows and process messages sent to those windows. User Interface (UI) threads create windows and process messages sent to those windows. User Interface thread has its own message pump. It can implement message maps and message handlers. Worker thread does not have its own message pump. User Interface thread has its own message pump. It can implement message maps and message handlers. Worker thread does not have its own message pump. User Interface thread has its own message pump. User Interface thread has its own message pump. Remains in the memory standby to do the work on receiving any message. Remains in the memory standby to do the work on receiving any message.

15 Creating UI Threads in MFC 1. Derive your own class from CWinThread 2. It must include its own override for InitInstance(). 3. Create a class, say CMyThread, derived from CWinThread. 4. Use DECLARE_DYNCREATE(CMyThread) macro in the class declaration. 5. Use IMPLEMENT_DYNCREATE(CMyThread, CWinThread) in implementation. 6. Create windows or any other thread functionality. 7. Launch UI thread by calling: CWinThread *pThread = AfxBeginThread(RUNTIME_CLASS(CMyThread)); or MyThread* pThread = new MyThread(); pThread->CreateThread(); pThread->CreateThread();

16 User Interface Thread Demo

17 Thread Termination ThreadFunc returns ThreadFunc returns Worker thread only Worker thread only Return value of 0 a normal return condition code Return value of 0 a normal return condition code WM_QUIT WM_QUIT UI thread only UI thread only AfxEndThread( UINT nExitCode ) AfxEndThread( UINT nExitCode ) Must be called by the thread itself Must be called by the thread itself

18 Thread Synchronization A Synchronizing threads means that every access to data shared between threads is protected so that when any thread starts an operation on the shared data no other thread is allowed access until the first thread is done. A Synchronizing threads means that every access to data shared between threads is protected so that when any thread starts an operation on the shared data no other thread is allowed access until the first thread is done. Critical Sections Critical Sections Mutexes Mutexes

19 MFC Critical Sections A critical section synchronizes access to a resource shared between threads, all in the same process. A critical section synchronizes access to a resource shared between threads, all in the same process. CCriticalSection constructs a critical section object CCriticalSection constructs a critical section object CCriticalSection::Lock() locks access to a shared resource for a single thread. CCriticalSection::Lock() locks access to a shared resource for a single thread. CCriticalSection::Unlock() unlocks access so another thread may access the shared resource CCriticalSection::Unlock() unlocks access so another thread may access the shared resource CCriticalSection cs; cs.Lock(); // operations on a shared resource, e.g., data, an iostream, file cs.Unlock(); CCriticalSection cs; cs.Lock(); // operations on a shared resource, e.g., data, an iostream, file cs.Unlock();

20 Win32 Mutexes To provide mutually exclusive access between different processes. To provide mutually exclusive access between different processes. CMutex constructs a mutex object CMutex constructs a mutex object Lock locks access for a single thread Lock locks access for a single thread Unlock releases the resource for acquisition by another thread CMutex cm; cm.Lock(); // access a shared resource cm.Unlock(); Unlock releases the resource for acquisition by another thread CMutex cm; cm.Lock(); // access a shared resource cm.Unlock(); CMutex objects are automatically released if the holding thread terminates. CMutex objects are automatically released if the holding thread terminates.


Download ppt "Threads and Thread Synchronization. Introduction In windows the basic unit of execution is the thread. It is the smallest schedulable unit of execution."

Similar presentations


Ads by Google