Spinlock Vs. Sleeping Lock Spinlock Implementation(1)

Total Page:16

File Type:pdf, Size:1020Kb

Spinlock Vs. Sleeping Lock Spinlock Implementation(1) Semaphores EECS 3221.3 • Problems with the software solutions. Operating System Fundamentals – Complicated programming, not flexible to use. – Not easy to generalize to more complex synchronization problems. No.6 • Semaphore (a.k.a. lock): an easy-to-use synchronization tool – An integer variable S Process Synchronization(2) – wait(S) { while (S<=0) ; S-- ; Prof. Hui Jiang } Dept of Electrical Engineering and Computer – signal(S) { Science, York University S++ ; } Semaphore usage (1): Semaphore usage (2): the n-process critical-section problem as a General Synchronization Tool • The n processes share a semaphore, Semaphore mutex ; // mutex is initialized to 1. • Execute B in Pj only after A executed in Pi • Use semaphore flag initialized to 0 Process Pi do { " wait(mutex);! Pi Pj " critical section of Pi! ! … … signal(mutex);" A wait (flag) ; signal (flag) ; B remainder section of Pi ! … … ! } while (1);" " " Spinlock vs. Sleeping Lock Spinlock Implementation(1) • In uni-processor machine, disabling interrupt before modifying • Previous definition of semaphore requires busy waiting. semaphore. – It is called spinlock. – spinlock does not need context switch, but waste CPU cycles wait(S) { in a continuous loop. do { – spinlock is OK only for lock waiting is very short. Disable_Interrupt; signal(S) { • Semaphore without busy-waiting, called sleeping lock: if(S>0) { S-- ; Disable_Interrupt ; – In defining wait(), rather than busy-waiting, the process makes Enable_Interrupt ; S++ ; system calls to block itself and switch to waiting state, and return ; Enable_Interrupt ; put the process to a waiting queue associated with the } return ; semaphore. The control is transferred to CPU scheduler. Enable_Interrupt ; } – In defining signal(), the process makes system calls to pick a } while(1) ; process in the waiting queue of the semaphore, wake it up by } moving it to the ready queue to wait for CPU scheduling. – Sleeping Lock is good only for long waiting. 1 Spinlock Implementation(1) Spinlock Implementation(2) • In multi-processor machine, inhibiting interrupt of all • In uni-processor machine, disabling interrupt before modifying processors is not easy and efficient. semaphore. • Use software solution to critical-section problems – e.g., bakery algorithm. wait(S) { – Treat wait() and signal() as critical sections. do { • Or use hardware support if available: signal(S) { Disable_Interrupt; – TestAndSet() or Swap() if(S>0) { S-- ; Disable_Interrupt ; Enable_Interrupt ; S++ ; • Example: implement spinlock among two processes. return ; Enable_Interrupt ; – Use Peterson’s algorithm for protection. } return ; – Shared data: Enable_Interrupt ; } while(1) ; } } Semaphore S ; Initially S=1 boolean flag[2]; initially flag [0] = flag [1] = false. int turn; initially turn = 0 or 1. Spinlock Implementation(3) Spinlock Implementation(2) wait(S) { • In multi-processor machine, inhibiting interrupt of all int i=process_ID(); //0P0, 1P1 signal(S) { processors is neither easy nor efficient. int i=process_ID(); //0P0, 1P1 int j=(i+1)%2 ; • Use software solution to critical-section problems int j=(i+1)%2 ; do { – e.g., bakery algorithm. flag [ i ]:= true; //request to enter – Treat wait() and signal() as critical sections. flag [ i ]:= true; //request to enter turn = j; • Or use hardware support if available: while (flag [ j ] and turn = j) ; turn = j; while (flag [ j ] and turn = j) ; – TestAndSet() or Swap() if (S >0) { //critical section S--; S++; //critical section • Example: implement spinlock between N processes. flag [ i ] = false; – Use Bakery algorithm for protection. return ; flag [ i ] = false; – Shared data: } else { flag [ i ] = false; return ; Semaphore S ; Initially S=1 } } } while (1); boolean choosing[N]; (Initially false) } int number[N]; (Initially 0 ) Spinlock Implementation(3) Sleeping Lock (I) wait(S) { int i=process_ID(); signal(S) { int i=process_ID(); • Define a sleeping lock as a structure: choosing[ i ] = true; number[ i ] = max(number[0], number[1], choosing[ i ] = true; typedef struct { …, number [N – 1])+1; number[ i ] = max(number[0], number[1], int value; // Initialized to 1 choosing[ i ] = false; …, number [N – 1])+1; for (j = 0; j < N; j++) { choosing[ i ] = false; struct process *L; while (choosing[ j ]) ; for (j = 0; j < N; j++) { } semaphore; while ((number[ j ] != 0) && while (choosing[ j ]) ; (number[ j ],j)< (number[ i ],i)) ; while ((number[ j ] != 0) && } (number[ j ],j)< (number[ i ],i)) ; • Assume two system calls: if (S >0) { //critical section } S--; – block() suspends the process that invokes it. number[i] = 0; S++; //critical section – wakeup(P) resumes the execution of a blocked process P. return ; } number[i] = 0; number[i] = 0; • Equally applicable to multiple threads in one process. } while (1); return ; } } 2 Sleeping Lock (II) Two Types of Semaphores: Binary vs. Counting • Semaphore operations now defined as: • Binary semaphore (a.k.a. mutex lock) – integer value wait(S): can range only between 0 and 1; simpler to implement S.value--; by hardware. if (S.value < 0) { add this process to S.L; • Counting semaphore – integer value can range over an block(); unrestricted domain. } signal(S): • We can implement a counting semaphore S by using S.value++; two binary semaphore. if (S.value <= 0) { remove a process P from S.L; • Binary semaphore is normally used as mutex lock. wakeup(P); } • Counting semaphore can be used as shared counter, load controller, etc… Implementing counting semaphore Implementing S with two Binary Semaphores • wait(S) operation: wait_binary(S1); C--; if (C < 0) { • Data structures: signal_binary(S1); binary-semaphore S1, S2; wait_binary(S2); int C: } signal_binary(S1); • Initialization: • signal(S) operation: S1 = 1 wait_binary(S1); S2 = 0 C ++; C = initial value of semaphore S if (C <= 0) signal_binary(S2); else signal_binary(S1); Bounded-Buffer P-C Problem Classical Synchronization Problems • A producer produces some data for a consumer to consume. They share a bounded-buffer for data • The Bounded-Buffer P-C Problem transferring. • Shared memory: A buffer to hold at most n items • The Readers-Writers Problem • Shared data (three semaphores) • The Dining-Philosophers Problem Semaphore filled, empty; /*counting*/ Semaphore mutex; /* binary */ Initially: filled = 0, empty = n, mutex = 1 3 Bounded-Buffer Problem: Bounded-Buffer Problem: Producer Process Consumer Process do { do { … wait(filled) produce an item in nextp wait(mutex); … … wait(empty); remove an item from buffer to nextc wait(mutex); … … add nextp to buffer signal(mutex); … signal(empty); signal(mutex); … signal(filled); consume the item in nextc … } while (1); } while (1); The Readers-Writers Problem The 1st Readers-Writers Problem • Many processes concurrently access a data object • Use semaphore to implement 1st readers-writer problem – Readers: only read the data. – Writers: update and may write the data object. • Shared data: • Only writer needs exclusive access of the data. int readcount = 0 ; // keep track the number of readers // accessing the data object • The first readers-writers problem: – Unless a writer has already obtained permission to use the shared data, readers are always allowed to access data. Semaphore mutex = 1 ; // mutually exclusive access to // readcount among readers – May starve a writer. • The second readers-writer problem: Semaphore wrt = 1 ; // mutual exclusion to the data object // used by every writer – Once a writer is ready, the writer performs its write as soon as possible. //also set by the 1st reader to read the data – May starve a reader. // and clear by the last reader to finish reading The Dining-Philosophers Problem The 1st Readers-Writers Problem • Five philosophers are Reader Process Writer Process thinking or eating …! • Using only five …! chopsticks wait(mutex);" wait(wrt);" readcount++; "" • When thinking, no need for chopsticks. …! if (readcount == 1) wait(wrt);" writing is performed! • When eating, need two signal(mutex);" closest chopsticks. …! …! • Can pick up only one signal(wrt);" reading is performed! chopsticks … …! • Can not get the one wait(mutex);" already in the hand of a readcount--;" neighbor. if (readcount == 0) signal(wrt);" signal(mutex);" … 4 The Dining-Philosophers Problem: Semaphore Solution Incorrect Semaphore Usage • Represent each chopstick with a semaphore Semaphore chopstick[5]; // Initialized to 1 Mistake 1: Mistake 2: Mistake 3: Mistake 4: do {" Philosopher i … … … wait(chopstick[i]) ;" … (i=0,1,2,3,4) signal(mutex) ; wait(mutex) ; wait(mutex) ; wait(chopstick[(i+1) % 5]) ;" Critical … … … …" Section Critical Critical Critical … eat! Section Section Section …" signal(mutex) ; … … … signal(chopstick[i]);" wait(mutex) ; wait(mutex) ; signal(chopstick[(i+1) % 5]);" …" think! …" } while (1); Starvation and Deadlock double_rq_lock() in Linux Kernel • Starvation – infinite blocking. A process may never be double_rq_lock(struct runqueue *rq1, removed from the semaphore queue in which it is struct runqueue *rq2) suspended. { if (rq1 == rq2) • Deadlock – two or more processes are waiting infinitely for an event that can be caused by only one of the waiting spinlock(&rq1->lock); processes. else { • Let S and Q be two semaphores initialized to 1 if (rq1 < rq2) { P0 P1 spin_lock(&rq1->lock); wait(S); wait(Q); spin_lock(&rq2->lock); wait(Q); wait(S); } else { spin_lock(&rq2->lock); signal(S); signal(Q); spin_lock(&rq1->lock); signal(Q) signal(S); } } } Why not? double_rq_unlock() in Linux Kernel double_rq_lock(struct runqueue *rq1, struct runqueue *rq2)
Recommended publications
  • Synchronization Spinlocks - Semaphores
    CS 4410 Operating Systems Synchronization Spinlocks - Semaphores Summer 2013 Cornell University 1 Today ● How can I synchronize the execution of multiple threads of the same process? ● Example ● Race condition ● Critical-Section Problem ● Spinlocks ● Semaphors ● Usage 2 Problem Context ● Multiple threads of the same process have: ● Private registers and stack memory ● Shared access to the remainder of the process “state” ● Preemptive CPU Scheduling: ● The execution of a thread is interrupted unexpectedly. ● Multiple cores executing multiple threads of the same process. 3 Share Counting ● Mr Skroutz wants to count his $1-bills. ● Initially, he uses one thread that increases a variable bills_counter for every $1-bill. ● Then he thought to accelerate the counting by using two threads and keeping the variable bills_counter shared. 4 Share Counting bills_counter = 0 ● Thread A ● Thread B while (machine_A_has_bills) while (machine_B_has_bills) bills_counter++ bills_counter++ print bills_counter ● What it might go wrong? 5 Share Counting ● Thread A ● Thread B r1 = bills_counter r2 = bills_counter r1 = r1 +1 r2 = r2 +1 bills_counter = r1 bills_counter = r2 ● If bills_counter = 42, what are its possible values after the execution of one A/B loop ? 6 Shared counters ● One possible result: everything works! ● Another possible result: lost update! ● Called a “race condition”. 7 Race conditions ● Def: a timing dependent error involving shared state ● It depends on how threads are scheduled. ● Hard to detect 8 Critical-Section Problem bills_counter = 0 ● Thread A ● Thread B while (my_machine_has_bills) while (my_machine_has_bills) – enter critical section – enter critical section bills_counter++ bills_counter++ – exit critical section – exit critical section print bills_counter 9 Critical-Section Problem ● The solution should ● enter section satisfy: ● critical section ● Mutual exclusion ● exit section ● Progress ● remainder section ● Bounded waiting 10 General Solution ● LOCK ● A process must acquire a lock to enter a critical section.
    [Show full text]
  • Synchronization: Locks
    Last Class: Threads • Thread: a single execution stream within a process • Generalizes the idea of a process • Shared address space within a process • User level threads: user library, no kernel context switches • Kernel level threads: kernel support, parallelism • Same scheduling strategies can be used as for (single-threaded) processes – FCFS, RR, SJF, MLFQ, Lottery... Computer Science CS377: Operating Systems Lecture 5, page 1 Today: Synchronization • Synchronization – Mutual exclusion – Critical sections • Example: Too Much Milk • Locks • Synchronization primitives are required to ensure that only one thread executes in a critical section at a time. Computer Science CS377: Operating Systems Lecture 7, page 2 Recap: Synchronization •What kind of knowledge and mechanisms do we need to get independent processes to communicate and get a consistent view of the world (computer state)? •Example: Too Much Milk Time You Your roommate 3:00 Arrive home 3:05 Look in fridge, no milk 3:10 Leave for grocery store 3:15 Arrive home 3:20 Arrive at grocery store Look in fridge, no milk 3:25 Buy milk Leave for grocery store 3:35 Arrive home, put milk in fridge 3:45 Buy milk 3:50 Arrive home, put up milk 3:50 Oh no! Computer Science CS377: Operating Systems Lecture 7, page 3 Recap: Synchronization Terminology • Synchronization: use of atomic operations to ensure cooperation between threads • Mutual Exclusion: ensure that only one thread does a particular activity at a time and excludes other threads from doing it at that time • Critical Section: piece of code that only one thread can execute at a time • Lock: mechanism to prevent another process from doing something – Lock before entering a critical section, or before accessing shared data.
    [Show full text]
  • Chapter 1. Origins of Mac OS X
    1 Chapter 1. Origins of Mac OS X "Most ideas come from previous ideas." Alan Curtis Kay The Mac OS X operating system represents a rather successful coming together of paradigms, ideologies, and technologies that have often resisted each other in the past. A good example is the cordial relationship that exists between the command-line and graphical interfaces in Mac OS X. The system is a result of the trials and tribulations of Apple and NeXT, as well as their user and developer communities. Mac OS X exemplifies how a capable system can result from the direct or indirect efforts of corporations, academic and research communities, the Open Source and Free Software movements, and, of course, individuals. Apple has been around since 1976, and many accounts of its history have been told. If the story of Apple as a company is fascinating, so is the technical history of Apple's operating systems. In this chapter,[1] we will trace the history of Mac OS X, discussing several technologies whose confluence eventually led to the modern-day Apple operating system. [1] This book's accompanying web site (www.osxbook.com) provides a more detailed technical history of all of Apple's operating systems. 1 2 2 1 1.1. Apple's Quest for the[2] Operating System [2] Whereas the word "the" is used here to designate prominence and desirability, it is an interesting coincidence that "THE" was the name of a multiprogramming system described by Edsger W. Dijkstra in a 1968 paper. It was March 1988. The Macintosh had been around for four years.
    [Show full text]
  • INF4140 - Models of Concurrency Locks & Barriers, Lecture 2
    Locks & barriers INF4140 - Models of concurrency Locks & barriers, lecture 2 Høsten 2015 31. 08. 2015 2 / 46 Practical Stuff Mandatory assignment 1 (“oblig”) Deadline: Friday September 25 at 18.00 Online delivery (Devilry): https://devilry.ifi.uio.no 3 / 46 Introduction Central to the course are general mechanisms and issues related to parallel programs Previously: await language and a simple version of the producer/consumer example Today Entry- and exit protocols to critical sections Protect reading and writing to shared variables Barriers Iterative algorithms: Processes must synchronize between each iteration Coordination using flags 4 / 46 Remember: await-example: Producer/Consumer 1 2 i n t buf, p := 0; c := 0; 3 4 process Producer { process Consumer { 5 i n t a [N ] ; . i n t b [N ] ; . 6 w h i l e ( p < N) { w h i l e ( c < N) { 7 < await ( p = c ) ; > < await ( p > c ) ; > 8 buf:=a[p]; b[c]:=buf; 9 p:=p+1; c:=c+1; 10 }} 11 }} Invariants An invariant holds in all states in all histories of the program. global invariant: c ≤ p ≤ c + 1 local (in the producer): 0 ≤ p ≤ N 5 / 46 Critical section Fundamental concept for concurrency Critical section: part of a program that is/needs to be “protected” against interference by other processes Execution under mutual exclusion Related to “atomicity” Main question today: How can we implement critical sections / conditional critical sections? Various solutions and properties/guarantees Using locks and low-level operations SW-only solutions? HW or OS support? Active waiting (later semaphores and passive waiting) 6 / 46 Access to Critical Section (CS) Several processes compete for access to a shared resource Only one process can have access at a time: “mutual exclusion” (mutex) Possible examples: Execution of bank transactions Access to a printer or other resources ..
    [Show full text]
  • CS350 – Operating Systems
    Outline 1 Processes and Threads 2 Synchronization 3 Memory Management 1 / 45 Processes • A process is an instance of a program running • Modern OSes run multiple processes simultaneously • Very early OSes only ran one process at a time • Examples (can all run simultaneously): - emacs – text editor - firefox – web browser • Non-examples (implemented as one process): - Multiple firefox windows or emacs frames (still one process) • Why processes? - Simplicity of programming - Speed: Higher throughput, lower latency 2 / 45 A process’s view of the world • Each process has own view of machine - Its own address space - Its own open files - Its own virtual CPU (through preemptive multitasking) • *(char *)0xc000 dierent in P1 & P2 3 / 45 System Calls • Systems calls are the interface between processes and the kernel • A process invokes a system call to request operating system services • fork(), waitpid(), open(), close() • Note: Signals are another common mechanism to allow the kernel to notify the application of an important event (e.g., Ctrl-C) - Signals are like interrupts/exceptions for application code 4 / 45 System Call Soware Stack Application 1 5 Syscall Library unprivileged code 4 2 privileged 3 code Kernel 5 / 45 Kernel Privilege • Hardware provides two or more privilege levels (or protection rings) • Kernel code runs at a higher privilege level than applications • Typically called Kernel Mode vs. User Mode • Code running in kernel mode gains access to certain CPU features - Accessing restricted features (e.g. Co-processor 0) - Disabling interrupts, setup interrupt handlers - Modifying the TLB (for virtual memory management) • Allows the kernel to isolate processes from one another and from the kernel - Processes cannot read/write kernel memory - Processes cannot directly call kernel functions 6 / 45 How System Calls Work • The kernel only runs through well defined entry points • Interrupts - Interrupts are generated by devices to signal needing attention - E.g.
    [Show full text]
  • 4. Process Synchronization
    Lecture Notes for CS347: Operating Systems Mythili Vutukuru, Department of Computer Science and Engineering, IIT Bombay 4. Process Synchronization 4.1 Race conditions and Locks • Multiprogramming and concurrency bring in the problem of race conditions, where multiple processes executing concurrently on shared data may leave the shared data in an undesirable, inconsistent state due to concurrent execution. Note that race conditions can happen even on a single processor system, if processes are context switched out by the scheduler, or are inter- rupted otherwise, while updating shared data structures. • Consider a simple example of two threads of a process incrementing a shared variable. Now, if the increments happen in parallel, it is possible that the threads will overwrite each other’s result, and the counter will not be incremented twice as expected. That is, a line of code that increments a variable is not atomic, and can be executed concurrently by different threads. • Pieces of code that must be accessed in a mutually exclusive atomic manner by the contending threads are referred to as critical sections. Critical sections must be protected with locks to guarantee the property of mutual exclusion. The code to update a shared counter is a simple example of a critical section. Code that adds a new node to a linked list is another example. A critical section performs a certain operation on a shared data structure, that may temporar- ily leave the data structure in an inconsistent state in the middle of the operation. Therefore, in order to maintain consistency and preserve the invariants of shared data structures, critical sections must always execute in a mutually exclusive fashion.
    [Show full text]
  • Lock (TCB) Block (TCB)
    Concurrency and Synchronizaon Mo0vaon • Operang systems (and applicaon programs) o<en need to be able to handle mul0ple things happening at the same 0me – Process execu0on, interrupts, background tasks, system maintenance • Humans are not very good at keeping track of mul0ple things happening simultaneously • Threads and synchronizaon are an abstrac0on to help bridge this gap Why Concurrency? • Servers – Mul0ple connec0ons handled simultaneously • Parallel programs – To achieve beGer performance • Programs with user interfaces – To achieve user responsiveness while doing computaon • Network and disk bound programs – To hide network/disk latency Definions • A thread is a single execu0on sequence that represents a separately schedulable task – Single execu0on sequence: familiar programming model – Separately schedulable: OS can run or suspend a thread at any 0me • Protec0on is an orthogonal concept – Can have one or many threads per protec0on domain Threads in the Kernel and at User-Level • Mul0-process kernel – Mul0ple single-threaded processes – System calls access shared kernel data structures • Mul0-threaded kernel – mul0ple threads, sharing kernel data structures, capable of using privileged instruc0ons – UNIX daemon processes -> mul0-threaded kernel • Mul0ple mul0-threaded user processes – Each with mul0ple threads, sharing same data structures, isolated from other user processes – Plus a mul0-threaded kernel Thread Abstrac0on • Infinite number of processors • Threads execute with variable speed – Programs must be designed to work with any schedule Programmer Abstraction Physical Reality Threads Processors 1 2 3 4 5 1 2 Running Ready Threads Threads Queson Why do threads execute at variable speed? Programmer vs. Processor View Programmers Possible Possible Possible View Execution Execution Execution #1 #2 #3 .
    [Show full text]
  • Kernel and Locking
    Kernel and Locking Luca Abeni [email protected] Monolithic Kernels • Traditional Unix-like structure • Protection: distinction between Kernel (running in KS) and User Applications (running in US) • The kernel behaves as a single-threaded program • One single execution flow in KS at each time • Simplify consistency of internal kernel structures • Execution enters the kernel in two ways: • Coming from upside (system calls) • Coming from below (hardware interrupts) Kernel Programming Kernel Locking Single-Threaded Kernels • Only one single execution flow (thread) can execute in the kernel • It is not possible to execute more than 1 system call at time • Non-preemptable system calls • In SMP systems, syscalls are critical sections (execute in mutual exclusion) • Interrupt handlers execute in the context of the interrupted task Kernel Programming Kernel Locking Bottom Halves • Interrupt handlers split in two parts • Short and fast ISR • “Soft IRQ handler” • Soft IRQ hanlder: deferred handler • Traditionally known ass Bottom Half (BH) • AKA Deferred Procedure Call - DPC - in Windows • Linux: distinction between “traditional” BHs and Soft IRQ handlers Kernel Programming Kernel Locking Synchronizing System Calls and BHs • Synchronization with ISRs by disabling interrupts • Synchronization with BHs: is almost automatic • BHs execute atomically (a BH cannot interrupt another BH) • BHs execute at the end of the system call, before invoking the scheduler for returning to US • Easy synchronization, but large non-preemptable sections! • Achieved
    [Show full text]
  • In the Beginning... Example Critical Sections / Mutual Exclusion Critical
    Temporal relations • Instructions executed by a single thread are totally CSE 451: Operating Systems ordered Spring 2013 – A < B < C < … • Absent synchronization, instructions executed by distinct threads must be considered unordered / Module 7 simultaneous Synchronization – Not X < X’, and not X’ < X Ed Lazowska [email protected] Allen Center 570 © 2013 Gribble, Lazowska, Levy, Zahorjan © 2013 Gribble, Lazowska, Levy, Zahorjan 2 Critical Sections / Mutual Exclusion Example: ExampleIn the beginning... • Sequences of instructions that may get incorrect main() Y-axis is “time.” results if executed simultaneously are called critical A sections Could be one CPU, could pthread_create() • (We also use the term race condition to refer to a be multiple CPUs (cores). situation in which the results depend on timing) B foo() A' • Mutual exclusion means “not simultaneous” – A < B or B < A • A < B < C – We don’t care which B' • A' < B' • Forcing mutual exclusion between two critical section C • A < A' executions is sufficient to ensure correct execution – • C == A' guarantees ordering • C == B' • One way to guarantee mutually exclusive execution is using locks © 2013 Gribble, Lazowska, Levy, Zahorjan 3 © 2013 Gribble, Lazowska, Levy, Zahorjan 4 CriticalCritical sections When do critical sections arise? is the “happens-before” relation • One common pattern: T1 T2 T1 T2 T1 T2 – read-modify-write of – a shared value (variable) – in code that can be executed concurrently (Note: There may be only one copy of the code (e.g., a procedure), but it
    [Show full text]
  • Energy Efficient Spin-Locking in Multi-Core Machines
    Energy efficient spin-locking in multi-core machines Facoltà di INGEGNERIA DELL'INFORMAZIONE, INFORMATICA E STATISTICA Corso di laurea in INGEGNERIA INFORMATICA - ENGINEERING IN COMPUTER SCIENCE - LM Cattedra di Advanced Operating Systems and Virtualization Candidato Salvatore Rivieccio 1405255 Relatore Correlatore Francesco Quaglia Pierangelo Di Sanzo A/A 2015/2016 !1 0 - Abstract In this thesis I will show an implementation of spin-locks that works in an energy efficient fashion, exploiting the capability of last generation hardware and new software components in order to rise or reduce the CPU frequency when running spinlock operation. In particular this work consists in a linux kernel module and a user-space program that make possible to run with the lowest frequency admissible when a thread is spin-locking, waiting to enter a critical section. These changes are thread-grain, which means that only interested threads are affected whereas the system keeps running as usual. Standard libraries’ spinlocks do not provide energy efficiency support, those kind of optimizations are related to the application behaviors or to kernel-level solutions, like governors. !2 Table of Contents List of Figures pag List of Tables pag 0 - Abstract pag 3 1 - Energy-efficient Computing pag 4 1.1 - TDP and Turbo Mode pag 4 1.2 - RAPL pag 6 1.3 - Combined Components 2 - The Linux Architectures pag 7 2.1 - The Kernel 2.3 - System Libraries pag 8 2.3 - System Tools pag 9 3 - Into the Core 3.1 - The Ring Model 3.2 - Devices 4 - Low Frequency Spin-lock 4.1 - Spin-lock vs.
    [Show full text]
  • Processes and Threads
    Interprocess Communication Yücel Saygın |These slides are based on your text book and on the slides prepared by Andrew S. Tanenbaum 1 Inter-process Communication • Race Conditions: two or more processes are reading and writing on shared data and the final result depends on who runs precisely when • Mutual exclusion : making sure that if one process is accessing a shared memory, the other will be excluded form doing the same thing • Critical region: the part of the program where shared variables are accessed 2 Interprocess Communication Race Conditions Two processes want to access shared memory at same time 3 Critical Regions (1) Four conditions to provide mutual exclusion 1. No two processes simultaneously in critical region 2. No assumptions made about speeds or numbers of CPUs 3. No process running outside its critical region may block another process 4. No process must wait forever to enter its critical region 4 Critical Regions (2) Mutual exclusion using critical regions 5 Mutual Exclusion via Disabling Interrupts • Process disables all interrupts before entering its critical region • Enables all interrupts just before leaving its critical region • CPU is switched from one process to another only via clock or other interrupts • So disabling interrupts guarantees that there will be no process switch • Disadvantage: – Should give the power to control interrupts to user (what if a user turns off the interrupts and never turns them on again?) – Does not work in case of multiple CPUs. Only the CPU that executes the disable instruction is effected. • Not suitable approach for the general case but can be used by the Kernel when needed 6 Mutual Exclusion with Busy Waiting: (1)Lock Variables • Testing a variable until some value appears is called busy waiting.
    [Show full text]
  • Synchronization Tools
    CHAPTER Synchronization 6 Tools Exercises 6.12 The pseudocode of Figure 6.15 illustrates the basic push() and pop() operations of an array-based stack. Assuming that this algorithm could be used in a concurrent environment, answer the following questions: a. What data have a race condition? b. How could the race condition be xed? 6.13 Race conditions are possible in many computer systems. Consider an online auction system where the current highest bid for each item must be maintained. A person who wishes to bid on an item calls the bid(amount) function, which compares the amount being bid to the current highest bid. If the amount exceeds the current highest bid, the highest bid is set to the new amount. This is illustrated below: void bid(double amount) { if (amount > highestBid) highestBid = amount; } Describe how a race condition is possible in this situation and what might be done to prevent the race condition from occurring. 6.14 The following program example can be used to sum the array values of size N elements in parallel on a system containing N computing cores (there is a separate processor for each array element): for j = 1 to log 2(N) { for k = 1 to N { if ((k + 1) % pow(2,j) == 0) { values[k] += values[k - pow(2,(j-1))] } } } 33 34 Chapter 6 Synchronization Tools This has the effect of summing the elements in the array as a series of partial sums, as shown in Figure 6.16. After the code has executed, the sum of all elements in the array is stored in the last array location.
    [Show full text]