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

Slides:



Advertisements
Similar presentations
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Advertisements

Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Operating Systems – Windows process and thread management In this lecture we will cover Threads and processes in Windows Thread priority.
CS444/CS544 Operating Systems Synchronization 2/21/2007 Prof. Searleman
SMP threads an Introduction to Posix Threads. Technical Definition 1.Independent stream of instructions that can be scheduled to run by an operating system.
Threads CNS What is a thread?  an independent unit of execution within a process  a "lightweight process"  an independent unit of execution within.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Slide 6-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6.
Win32 Programming Lesson 9: Jobs & Thread Basics.
Introduction to Processes CS Intoduction to Operating Systems.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
MultiThreaded Applications. What is Multithreaded Programming? Having your software appear to perform multiple tasks in parallel –Individual paths of.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
CE Operating Systems Lecture 11 Windows – Object manager and process management.
Threads and Thread Synchronization Advanced Windows Programming Series 1.
1 Confidential Enterprise Solutions Group Process and Threads.
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Java Thread and Memory Model
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Threads A thread is an alternative model of program execution
Windows CE Portable Modular Real-time Small footprint Embedded market.
Windows Threading Colin Roby Jaewook Kim.
Operating Systems CMPSC 473 Signals, Introduction to mutual exclusion September 28, Lecture 9 Instructor: Bhuvan Urgaonkar.
Threads and Thread Synchronization in MFC By Gregory Mortensen CSIS 4330 Advanced Windows Programming.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
Window Threads Chapter 7 Windows Thread Management.
LPC2148's RTOS Bruce Chhuon 4/10/07. What is a Real Time Operating System? ● A Real Time Operating System (RTOS) manages hardware and software resources.
Realizing Concurrency using the thread model
Win32 Threads and Thread Synchronization
PROCESS MANAGEMENT IN MACH
Realizing Concurrency using the thread model
Day 12 Threads.
Concurrency, Processes and Threads
Threads Threads.
Lecture 7 : Multithread programming
Konstantin Bukin CSE791 – Advanced Windows Programming Summer 2001
Multithreading Tutorial
Operating Systems: A Modern Perspective, Chapter 6
Threads and Thread Synchronization
Principles of Operating Systems Lecture 8
Threads and Locks.
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Multithreading.
PTHREADS AND SEMAPHORES
Realizing Concurrency using the thread model
Unix System Calls and Posix Threads
Multithreading.
Chapter 05. Multithread.
Threading using C# and .Net
Multithreaded Programming
Threads Chapter 5 2/17/2019 B.Ramamurthy.
Windows Development Dynadata Copyright, 2014 © DynaData S.A. 1/49.
Multithreading Tutorial
Threads Chapter 5 2/23/2019 B.Ramamurthy.
Concurrency, Processes and Threads
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Implementing Processes, Threads, and Resources
Multithreading in java.
Presentation transcript:

Threads and Thread Synchronization

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.

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

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

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

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

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.

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).

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.

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.

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 );

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.

Demo Worker Thread

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.

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();

User Interface Thread Demo

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

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

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();

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.