Win32 Programming Lesson 11: User-mode Thread Sync (aka: How to crash your machine without really trying…)

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 10 SHARED MEMORY.
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Silberschatz, Galvin and Gagne ©2007 Operating System Concepts with Java – 7 th Edition, Nov 15, 2006 Chapter 6 (a): Synchronization.
Previously… Processes –Process States –Context Switching –Process Queues Threads –Thread Mappings Scheduling –FCFS –SJF –Priority scheduling –Round Robin.
Mutual Exclusion.
Interprocess Communication
CS444/CS544 Operating Systems Synchronization 2/21/2006 Prof. Searleman
Concurrency.
CS444/CS544 Operating Systems Synchronization 2/16/2007 Prof. Searleman
Race Conditions Critical Sections Deker’s Algorithm.
Avishai Wool lecture Introduction to Systems Programming Lecture 4 Inter-Process / Inter-Thread Communication.
Semaphores. Announcements No CS 415 Section this Friday Tom Roeder will hold office hours Homework 2 is due today.
Synchronization Principles. Race Conditions Race Conditions: An Example spooler directory out in 4 7 somefile.txt list.c scores.txt Process.
Introduction to Synchronization CS-3013 A-term Introduction to Synchronization CS-3013, Operating Systems A-term 2009 (Slides include materials from.
1 Outline Processes Threads Inter-process communication (IPC) Classical IPC problems Scheduling.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
1 Race Conditions/Mutual Exclusion Segment of code of a process where a shared resource is accessed (changing global variables, writing files etc) is called.
CSE 380 – Computer Game Programming Render Threading Portal, by Valve,
Win32 Programming Lesson 9: Jobs & Thread Basics.
1 Thread Synchronization: Too Much Milk. 2 Implementing Critical Sections in Software Hard The following example will demonstrate the difficulty of providing.
Multi-Threading and Load Balancing Compiled by Paul TaylorCSE3AGR Stolen mainly from Orion Granatir
Nachos Phase 1 Code -Hints and Comments
Win32 Programming Lesson 13: Thread Pooling (Wow, Java is good for something…)
Win32 Programming Lesson 10: Thread Scheduling and Priorities.
Win32 Programming Lesson 22: DLL Magic Part Deux All your base are belong to us…
CSE451 NT Synchronization Autumn 2002 Gary Kimura Lecture #9 October 18, 2002.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Mutual Exclusion.
COMP 111 Threads and concurrency Sept 28, Tufts University Computer Science2 Who is this guy? I am not Prof. Couch Obvious? Sam Guyer New assistant.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
11/18/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
Kernel Locking Techniques by Robert Love presented by Scott Price.
Java Thread and Memory Model
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
Windows CE Overview and Scheduling Presented by Dai Kawano.
1 Previous Lecture Overview  semaphores provide the first high-level synchronization abstraction that is possible to implement efficiently in OS. This.
Operating Systems CMPSC 473 Signals, Introduction to mutual exclusion September 28, Lecture 9 Instructor: Bhuvan Urgaonkar.
Uses some of the slides for chapters 7 and 9 accompanying “Introduction to Parallel Computing”, Addison Wesley, 2003.
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
CS 153 Design of Operating Systems Winter 2016 Lecture 7: Synchronization.
CSC 660: Advanced Operating SystemsSlide #1 CSC 660: Advanced OS Synchronization.
1 Critical Section Problem CIS 450 Winter 2003 Professor Jinhua Guo.
Implementing Mutual Exclusion Andy Wang Operating Systems COP 4610 / CGS 5765.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
CS162 Section 2. True/False A thread needs to own a semaphore, meaning the thread has called semaphore.P(), before it can call semaphore.V() False: Any.
Java Thread Programming
CSE 120 Principles of Operating
CS703 – Advanced Operating Systems
Atomic Operations in Hardware
Atomic Operations in Hardware
Synchronization Issues
Background and Motivation
Grades.
Implementing Mutual Exclusion
Explaining issues with DCremoval( )
Implementing Mutual Exclusion
Kernel Synchronization II
Userspace Synchronization
CSE 451: Operating Systems Autumn 2004 Module 6 Synchronization
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
CSE 153 Design of Operating Systems Winter 19
CS333 Intro to Operating Systems
Foundations and Definitions
EE 155 / COMP 122: Parallel Computing
EN Software Carpentry Python – A Crash Course Esoteric Sections Parallelization
Synchronization CS Spring 2002.
Presentation transcript:

Win32 Programming Lesson 11: User-mode Thread Sync (aka: How to crash your machine without really trying…)

Where are we?  We’ve got thread basics worked out… even priorities  But right now, all the examples are sort-of contrived…  Need to understand how to communicate from thread to thread

Thread Problems  When we share data between threads, bad things can happen  Look at the following example code…  What’s wrong?  Can replace using “interlocked” functions

InterlockedExchangeAdd  LONG InterlockedExchangeAdd ( PLONG plAddend, LONG lIncrement );  What could be simpler – promises Atomic access to *plAddend

Family  LONG InterlockedExchange( PLONG plTarget, LONG lValue );  PVOID InterlockedExchangePointer( PVOID* ppvTarget, PVOID pvValue );

Spinlock…  // Global variable indicating whether a shared re source is in use or not BOOL g_fResourceInUse = FALSE; void Func1() { // Wait to access the resource. while (InterlockedExchange ( &g_fResourceInUse, TRUE) == TRUE) Sleep(0); // Access the resource. // We no longer need to access the resource. InterlockedExchange(&g_fResourceInUse, FALSE); }

Spinlocks (cntd)  Be careful on a single processor machine  Is Sleep(0) the best call? Why?

More Interlocked Calls…  PVOID InterlockedCompareExchange( PLONG plDestination, LONG lExchange, LONG lComparand );  PVOID InterlockedCompareExchangePointer( PVOID* ppvDestination, PVOID pvExchange, PVOID pvComparand );  Basically, update on equality…

Cashing in… (groan)  When a CPU accesses memory, it does not read a single byte, but instead fills a “cache line” (32 or 64 bytes, aligned on a 32 or 64 byte boundary)  If the cache becomes dirty it is flushed  Has a huge impact on how to design data structures for speed

_declspec(align32)  See MSDNMSDN  Basically, forces alignment on a cache boundary  See: declspec example…

DON’T DO THIS!  volatile BOOL g_fFinishedCalculation = FALSE; int WINAPI WinMain(...) { CreateThread(..., RecalcFunc,...); // Wait for the recalculation to complete. while (!g_fFinishedCalculation) ; } DWORD WINAPI RecalcFunc(PVOID pvParam) { // Perform the recalculation. g_fFinishedCalculation = TRUE; return(0); }

Volatile?  Well? Well?  Oops (optimizer…): ; Copy the value into a register Label: MOV Reg0, [g_fFinishedCalculation] TEST Reg0, 0; Is the value 0? JMP Reg0 == 0, Label; The register is 0, try again... ; The register is not 0 (end of loop)

Critical Section  Can mark a code section as critical  This prevents any other thread accessing the resources within the critical section  Other threads do still get scheduled though…

Look at this…  const int MAX_TIMES = 1000; int g_nIndex = 0; DWORD g_dwTimes[MAX_TIMES]; DWORD WINAPI FirstThread(PVOID pvParam) { while (g_nIndex < MAX_TIMES) { g_dwTimes[g_nIndex] = GetTickCount(); g_nIndex++; } return(0); } DWORD WINAPI SecondThread(PVOID pvParam) { while (g_nIndex < MAX_TIMES) { g_nIndex++; g_dwTimes[g_nIndex - 1] = GetTickCount(); } return(0); }

Fixed..  const int MAX_TIMES = 1000; int g_nIndex = 0; DWORD g_dwTimes[MAX_TIMES]; CRITICAL_SECTION g_cs; DWORD WINAPI FirstThread(PVOID pvParam) { while (g_nIndex < MAX_TIMES) { EnterCriticalSection(&g_cs); g_dwTimes[g_nIndex] = GetTickCount(); g_nIndex++; LeaveCriticalSection(&g_cs); } return(0); } DWORD WINAPI SecondThread(PVOID pvParam) { while (g_nIndex < MAX_TIMES) { EnterCriticalSection(&g_cs); g_nIndex++; g_dwTimes[g_nIndex - 1] = GetTickCount(); LeaveCriticalSection(&g_cs); } return(0); }

But…  You MUST remember to leave a critical section else no other thread can use the resource  And the Devil really is in the details

Initialization  Before you can use a CRITICAL SECTION you must initialize it VOID InitializeCriticalSection(PCRITICAL_SE CTION pcs); Results undefined if you don’t do this… BTW, what do you notice about the return?

Entering…  If no thread is using the resource, continue  Else put the calling thread into a WAIT state  VOID EnterCriticalSection(PCRITICAL_SE CTION pcs);  Can use: BOOL TryEnterCriticalSection(PCRITICAL_SE CTION pcs); Don’t wait: return TRUE/FALSE

Leaving  VOID LeaveCriticalSection(PCRITICAL_SE CTION pcs);  If we’re done with this Section check for any other threads waiting and mark 1 as schedulable  VOID DeleteCriticalSection(PCRITICAL_SE CTION pcs);

Tips  Use ONE critical section per shared resource  Access multiple resources using multiple critical sections  Don’t hold on to a critical section for a long time

Next…  Thread Synchronization with Kernel objects