Lab 1 The Alarm Clock (Threads and Semaphores)

Similar documents
Tentamen EDAF85/EDA698 Realtidssystem (Helsingborg)

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Java Programming Constructs Java Programming 2 Lesson 1

Exercises and Labs. Part I. Exercises

Boot Camp. Dave Eckhardt Bruce Maggs

Lab Exercise Test First using JUnit

Operating Systems, Assignment 2 Threads and Synchronization

LookoutDirect Basics: Windows, Tools, Files, and Path Names

SYNCHRONIZED DATA. Week 9 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer. Pre-Laboratory Checklist

LAB 7 Writing Assembly Code

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

Java Threads and intrinsic locks

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Real-Time and Concurrent Programming Lecture 1 (F1): Embedded concurrent software

Using Eclipse for Java. Using Eclipse for Java 1 / 1

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax

Resource 2 Embedded computer and development environment

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

Getting to know Greenfoot

Advanced Programming - CS239

3 Getting Started with Objects

Introduction. Key features and lab exercises to familiarize new users to the Visual environment

Building a safe and secure embedded world. Testing State Machines. and Other Test Objects Maintaining a State. > TESSY Tutorial Author: Frank Büchner

Starting Microsoft Visual Studio 6.0 And Exploring Available Controls Tools

CPS 310 second midterm exam, 11/14/2014

ETS110: Internet Protocol Routing Lab Assignment

ETS110: Internet Protocol Routing Lab Assignment

ASSIGNMENT 5 Objects, Files, and More Garage Management

Micrium OS Kernel Labs

ASSIGNMENT 5 Objects, Files, and a Music Player

Creating Folders in Foliotek

Summer Assignment for AP Computer Science. Room 302

Lab 3b: Scheduling Multithreaded Applications with RTX & uvision

Excel Tips to help you with the PS477/577 Final Paper Project

Dealing with Issues for Interprocess Communication

NetBeans Tutorial. For Introduction to Java Programming By Y. Daniel Liang. This tutorial applies to NetBeans 6, 7, or a higher version.

Chapter 4 Defining Classes I

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

TDDD56 Multicore and GPU computing Lab 2: Non-blocking data structures

GE420 Laboratory Assignment 3 More SYS/BIOS

DOMAIN TECHNOLOGIES. Getting Started Guide Version 1.1. BoxView IDE. Integrated Development Environment

5. Synchronization. Operating System Concepts with Java 8th Edition Silberschatz, Galvin and Gagn

Programming Assignment #4 Writing a simple parallel port device driver

Exam Concurrent and Real-Time Programming

Drools Tools Reference Guide. Version: CR1

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Laboratory 1: Eclipse and Karel the Robot

INF 111 / CSE 121. Homework 3: Code Reading

LARGE SCALE IP ROUTING

CSC207 Week 4. Larry Zhang

ETSF05: Internet Protocol Routing Project Assignment

Atropos User s manual

Reminder from last time

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists

3 TUTORIAL. In This Chapter. Figure 1-0. Table 1-0. Listing 1-0.

Introduction to programming the FRDM/MBED in Java David J.

Synchronization (Part 2) 1/40

Fall 2004 CS414 Prelim 1

How to program with Matlab (PART 1/3)

Performance of Telecommunication Networks

SmartCVS Tutorial. Starting the putty Client and Setting Your CVS Password

Using LookoutDirect. Overview of the Process Development Cycle

EECS 678: Intro to Operating Systems Programming Assignment 3: Virtual Memory in Nachos

Assignment 1. Application Development

Operating System Services

CS 134 Programming Exercise 3:

THE UNIVERSITY OF WESTERN AUSTRALIA SAMPLE EXAM QUESTIONS 2007 WITH SOLUTIONS SCHOOL OF COMPUTER SCIENCE CITS3213 CONCURRENT PROGRAMMING (PART II)

cs 140 project 1: threads 9 January 2015

Synchronization 1. Synchronization

Getting Started with the HCS12 IDE

Interrupts and Time. Real-Time Systems, Lecture 5. Martina Maggio 28 January Lund University, Department of Automatic Control

UNIVERSITY OF OSLO. Faculty of Mathematics and Natural Sciences

Xilinx Vivado/SDK Tutorial

Interrupts and Time. Interrupts. Content. Real-Time Systems, Lecture 5. External Communication. Interrupts. Interrupts

Computer Basics: Step-by-Step Guide (Session 2)

Mr.Kailley s AP Chem programming Unit Set up instruction sheet for PC s (Mac will be kind of similar: good luck) 1) Go to the following website:

Good Coding Practices Spring 2018

F28335 ControlCard Lab1

Virtual Machine Design

Lab 9 Loops, Debugging

Lab 3a: Scheduling Tasks with uvision and RTX

Exam Concurrent and Real-Time Programming

CSE 153 Design of Operating Systems

Instructions PLEASE READ (notice bold and underlined phrases)

AP Computer Science A Magpie Chatbot Lab Student Guide

CPS 310 first midterm exam, 10/6/2014

EE121 Foundation Review Session Page 1 of 16 Winter Learning to Love Xilinx Foundation 4.1i in 40 Easy Steps

Getting Started (1.8.7) 9/2/2009

NI LabView READ THIS DOCUMENT CAREFULLY AND FOLLOW THE INSTRIUCTIONS IN THE EXERCISES

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

1. Consider the following page reference string: 1, 2, 3, 4, 2, 1, 5, 6, 2, 1, 2, 3, 7, 6, 3, 2, 1, 2, 3, 6.

1 Process Coordination

Synchronization I. Jo, Heeseung

Lab 5 Random numbers!

Getting Started with Web Services

Quick Guide. Choose It Maker 2. Overview/Introduction. ChooseIt!Maker2 is a motivating program at first because of the visual and musical

Operating Systems. Synchronization

Using the Zoo Workstations

Lab Exercise 6: Abstract Classes and Interfaces CS 2334

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Transcription:

Exercises and Labs Lab 1 The Alarm Clock (Threads and Semaphores) Exercise session - preparation In this exercise you will design a real-time system for an alarm clock application using threads, semaphores and provided hardware emulation. In lab 1 you will implement your design (the implementation usually takes longer than two hours so be sure to start well in advance of the review occasion). Objective After this design and programming exercise you will have implemented the real-time software for a small embedded system. You should know the following terms: Sporadic and periodic threads Semaphore and be able to Use semaphores for signaling and mutual exclusion Share data between threads through a passive object protected by a semaphore Design small realtime systems containing both event-driven and periodic activities You will know the di erence between sporadic and periodic threads, and you will know how the use the semaphore primitive for signaling and mutual exclusion. You will know how to design a small realtime system with two threads. Preparation and design Study the provided specification, description of the handout code and hardware emulator and answer the following questions (express your design in class diagrams and Java code where necessary): 1. What parallel activities are needed, i.e., which thread objects do you need? 2. What common data need to be shared between threads? Where are the data to be stored? 3. What operations on data are needed for each thread? Where should this logic be stored? 25

Multi-Threaded Programming in Java 4. Where will data be accessed concurrently from di erent threads, i.e., where do you need to provide mutual exclusion? 5. Are there other situations in the alarm clock where semaphores are needed for synchronization? Hint: study the ClockInput class. 6. If you in a thread wait for the next second by simply calling sleep(1000), what will the e ect on the clock time be? Is this ok for alarm clock time updating? Can it be improved? Specification 1. The displayed clock time should be updated every second (by calling the ClockOutput.showTime method). Note: when the user has selected set alarm or set time, the hardware/emulator shows the set time and an update of the clock time will have no e ect on the clock display. Still, the clock time should be updated every second regardless of mode. 2. It should be possible to set the clock time and the alarm time. The hardware emulator internally handles the actual setting/editing of the time value. When the user selects another mode, the set value is written to the ClockInput object and give is called for its semaphore. For example, the user selects set alarm and edits (using number keys or arrows) the alarm time. Nothing needs to be done by the control software. Then the user selects set time and the alarm time is written to the ClockInput object and give is called. Note: give is called for each key press or interaction with the alarm clock. It is therefore necessary to filter signals according to the comment in ClockInput.getValue. 3. When the clock time is equal to the alarm time, and the alarm on tick box is selected, the alarm should beep once a second for 20 seconds. The ClockOutput.doAlarm() method provides one beep. The sound should be turned o if the user pushes any button while the alarm is sounding. 4. The program should later on be written in Java, using the Thread class. Signalling and mutual exclusion shall be achieved through semaphores according to the se.lth.cs.realtime package. 26 5. Optional: Include in your design an AlarmClock.terminate() method. The terminate method should result in termination of all your threads, before returning to the caller.

Exercises and Labs Using the emulator Start the AlarmClock (through Eclipse) as an applet. First, you must click somewhere on the image of the clock to give the applet keyboard focus (light blue area). Clicking the check box or another window will steal keyboard focus again. Hold Shift to set clock time (button 1). Hold Ctrl to set alarm time (button 3) 2. Hold Shift+Ctrl to toggle alarm on or o. Use direction keys for buttons 2-6. The two lines on the LCD display should be fairly obvious. The first line displays the current clock time. The second line displays the alarm time. When the alarm is set the separators in the alarm time turn into colons, otherwise they remain as underscores. When the alarm is beeping the separators will flash with the beeps of the alarm. Below the buttons is a small status field which displays the alarm status with a check box and the current input mode with three radio buttons. The radio buttons may not be manipulated directly, but the check box can be used to modify the alarm status (on/o ). When either of the modes Set Time or Set Alarm is active the user may increase the digit under the cursor (indicated by an underscore) by pressing the up button (2), decrease the digit under the cursor with the down button (5), shift cursor left with the left button (4) and shift cursor right with the right button (6). Handout code The handout code consists of two Java packages called done and todo. Thedone package contains the emulator (as an applet) as well as hardware interfaces (ClockInput and ClockOutput). The todo package will contain your real-time system. todo right now contains one class, AlarmClock, that contains a sample implementation that beeps upon key presses. You will modify and extend todo with classes as you deem necessary for your implementation. 2 Note for Mac OS X users: in case your computer behaves strangely upon pressing Ctrl, it can be a good idea to switch from KeyEvent.VK_CTRL to something less meaningful, e.g., KeyEvent.VK_COMMA in the ClockGUI.keyPressed and ClockGUI.keyReleased methods respectively (in package done). 27

Multi-Threaded Programming in Java AlarmClock class package todo; import done.*; import se.lth.cs.realtime.semaphore.semaphore; import se.lth.cs.realtime.semaphore.mutexsem; public class AlarmClock extends Thread { private static ClockInput input; private static ClockOutput output; private static Semaphore sem; public AlarmClock(ClockInput i, ClockOutput o) { input = i; output = o; sem = input.getsemaphoreinstance(); // The AlarmClock thread is started by the simulator. No // need to start it by yourself, if you do you will get // an IllegalThreadStateException. The implementation // below is a simple alarmclock thread that beeps upon // each keypress. To be modified in the lab. A recommendation // is to use this thread to start up your system similar // to RTsemBuffer in exercise 1. public void run() { while (true) { sem.take(); output.doalarm(); Looking inside the simulator for a moment, what is happening at startup is that the simulator creates an instance of your AlarmClock class and starts a new thread on the resulting object. The new thread starts executing in the AlarmClock.run() method. Simulator excerpt: AlarmClock startup code ClockInput butt2ctrl; // Interface to user actions via hardware/software. ClockOutput ctrl2disp; // Interface to display hardware/software. AlarmClock control; // The actual alarm-clock software. //... control = new AlarmClock(butt2ctrl, ctrl2disp); control.start(); In the same manner, when the applet is stopped (corresponding to hardware reset), there is a call control.terminate(); which you need to override, if you want to fulfil the optional specification item 5. The following classes are the ClockOutput and the ClockInput that describe the interface between the control software and the clock hardware/emulator. 28

Exercises and Labs Excerpt from the ClockOutput class public class ClockOutput { * Wake-up clock user. public void doalarm() {... * If the display is currently used to display the time, update it. * If user is using display for setting clock or alarm time, do * nothing. public void showtime(int hhmmss) {... Excerpt from the ClockInput class public class ClockInput { * Semaphore that signals when the user has changed any setting. * Get-method to access the semaphore instance directly. public Semaphore getsemaphoreinstance() {... * Get check-box state. public boolean getalarmflag() {... * Return values for getchoice. public static final int SHOW_TIME = 0; public static final int SET_ALARM = 1; public static final int SET_TIME = 2; * Get radio-buttons choice. public int getchoice() {... * When getchoice returns a new choice, and the previous choice * was either SET_ALARM or SET_TIME, the set-value of the display * is returned in the format hhmmss where h, m, and s denotes * hours, minutes, and seconds digits respectively. This means, * for example, that the hour value is obtained by dividing the * return value by 10000. * Make sure to wait until a new choice has been reported before * deciding what to do public int getvalue() {... Some advice Originally, this exercise aimed at a physical alarm clock, where the hardware expected (minimal) C-code. The respective Java to C translator cannot cope with the entire Java language and framework. Keeping in mind that the translator s requirements would be necessary to fulfill, you should try to stick to these constraints also when only using the emulator and pure Java. This means to keep your design as minimal as possible, specifically the number of threads should be kept small for the design. 29

Multi-Threaded Programming in Java Checklist for self- and peer assessment of your design You should be able to answer the following questions with yes before asking your teacher for approval of your design: Is there a minimal number of active objects (threads) in the design? Is there some passive object (data storage) to maintain the current clock and alarm times? Is the design supporting mutually exclusive access to data accessed by di erent threads? Is there an activity (thread) designated to take care of user input (button presses)? Is there an activity (thread) designated to handle the clock updates? Are all relevant functionalities (see specification) planned to be taken care of by respective methods? Are calculations planned to be made at the right place (data / monitor logic, vs thread logic)? Once you assume all questions positively answered for your own design, hand it over to your partner group for cross checking. Do the same check for the other group s design. After getting a confirmation for the checklist, show your solution to the teacher. All students in your group need to be able to explain the design for approval! 30

Multi-Threaded Programming in Java Laboratory session - programming You are now supposed to implement your alarm clock system designed in the previous exercise. The actual target system is an AVR board equipped with LCD display and six buttons (as shown in the image), for which it is required to use a Java-to-C compiler, as the hardware only can handle C code. However, for this course you will only implement the alarm clock in Java using semaphores and execute it on the Java emulator provided through the course workspace (see the respective.zip-file provided on the course web). Still, you should design and write your program according to the instructions and advice that would be necessary for the cross-compilation. Programming advice It is generally a good idea to start programming before the lab occasion. You should use both the emulator and the code stubs provided in the Eclipse workspace which is available as a.zip-file from the course web page. Remember that the emulator should be run as an applet. Before you start programming you need to have your design of the system approved by your teacher. If you do not have this approval, start over with the preparation exercise! Inspect the code skeleton and prepared classes in the AlarmClock project s done and todo folders. You will implement your real-time system in the todo folder by modifying the present AlarmClock class and adding further classes as your design requires. Some advice The Java to C translator cannot cope with the entire Java language and framework. Keeping in mind that the translator s requirements would be necessary to fulfill, you should try to stick to these constraints also when only using the emulator and pure Java. Also, from an embedded systems point of view it is best to import as little as possible to minimize memory requirements. Avoid * when importing, just import the classes that are needed 3. For the lab a very small subset is necessary: 3 A comment on LJRT: The curious reader might wonder why we use an inhouse package to provide synchronization primitives. The explanation is that the LJRT package (Lund Java Real-Time) was specifically developed to support Java to C translation for small embedded systems. During translation the LJRT Java primitives are replaced by their C counterparts. The translation tool we use was developed as part of a doctoral real-time thesis presented a few years back. The tool is now hosted on https://launchpad.net/ljrt. 32

Exercises and Labs Thread System.currentTimeMillis() LJRT semaphores se.lth.cs.realtime.semaphore.semaphore se.lth.cs.realtime.semaphore.mutexsem se.lth.cs.realtime.semaphore.countingsem You are (in this lab) only allowed to use take and give operations on the semaphores, trytake is forbidden. Checklist and hints for self- and peer assessment (and correction) of the implementation You should be able to answer the following questions with yes before asking your teacher for approval of your program: Does the program correspond to the approved design (in case it does not, is there an acceptable reason)? Does the program (applet) work according to specifications (check against the given specification, if there are deviations, debug the respective methods, or simply add the forgotten functionality, check that your threads are started properly)? Is (according to the program code) mutual exclusion handled appropriately (any data manipulation should be protected by a semaphore, use several MutexSems only when absolutely sure about what you are doing and why, otherwise one instance is su cient - and safest)? Are (according to the program code) signals handled appropriately (no busy waits, i.e., no loops that keep running and checking some condition instead of an eternal loop that is blocked by waiting on a signalling semaphore)? Is made sure (according to the program code) that there is no unnecessary handling of input data (check the getchoice / getvalue specification and use of those methods, only when the choice is changed FROM certain choice-values, the respective time value should be handled)? Is the clock update correctly handled (i.e., no accumulative error in time calculations, see remarks on Time in the booklet, and make sure the code follows the principles for one as exact as possible update per second)? A hint on the display during input: In case you get cryptic signs instead of the expected numbers, check your conditions for when to retrieve and update the time / alarm time values against the specification. In case you get stuck beyond the hints given above, consult with your partner group first, then turn to the lab assistant or teacher for help. Once you assume all questions positively answered for your own implementation, hand it over to your partner group for cross checking. Do the same check for the other group s implementation. After getting a confirmation for the checklist, show your program to the teacher. All students in your group need to be able to explain the program for approval! 33