Robotics and Autonomous Systems

Similar documents
ROBOTICS AND AUTONOMOUS SYSTEMS

Building Robots with NXT and LEJOS. Introduc<on. What is the NXT Robot Michael Wooldridge liv.ac.uk)

JAVA - MULTITHREADING

OBJECT ORIENTED PROGRAMMING LANGUAGE

Outline of this lecture G52CON: Concepts of Concurrency

Topics. Producing Production Quality Software. Concurrent Environments. Why Use Concurrency? Models of concurrency Concurrency in Java

Threads 1. When writing games you need to do more than one thing at once.

Multithreaded Programming

Tutorial: Getting Started

CS11 Java. Fall Lecture 7

Linux Process Scheduling Policy

SYSTEM ecos Embedded Configurable Operating System

Mutual Exclusion using Monitors

Java Memory Model: Content

Crash Course in Java

Threads & Tasks: Executor Framework

Creating a Simple, Multithreaded Chat System with Java

Java Interview Questions and Answers

Real-Time Systems Prof. Dr. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Monitors, Java, Threads and Processes

Java Troubleshooting and Performance

Java Concurrency Framework. Sidartha Gracias

Getting Started with the Internet Communications Engine

What are exceptions? Bad things happen occasionally

An Overview of Java. overview-1

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

ADT Implementation in Java

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Virtual Machine Locks

Week 2 Practical Objects and Turtles

Java SE 8 Programming

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

public static void main(string[] args) { System.out.println("hello, world"); } }

Thesis Proposal: Improving the Performance of Synchronization in Concurrent Haskell

Chapter 8 Implementing FSP Models in Java

Parallel Programming

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Last Class: Semaphores

Line Tracking Basic Lesson

3C03 Concurrency: Condition Synchronisation

A Thread Monitoring System for Multithreaded Java Programs

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

JAVA Program For Processing SMS Messages

Concurrent programming in Java

STM32JAVA. Embedded Java Solutions for STM32

Fundamentals of Java Programming

Lecture J - Exceptions

Scheduling recurring tasks in Java applications

Operating System Resource Management. Burton Smith Technical Fellow Microsoft Corporation

Hoare-Style Monitors for Java

Computer Science 483/580 Concurrent Programming Midterm Exam February 23, 2009

Chapter 6 Concurrent Programming

Operating Systems Concepts: Chapter 7: Scheduling Strategies

Monitors (Deprecated)

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Web Development in Java

Semaphores and Monitors: High-level Synchronization Constructs

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Concurrent Programming

ECE 122. Engineering Problem Solving with Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

1.1. Over view Example 1: CPU Slot Distribution A example to test the distribution of cpu slot.

Background Tasks and Blackboard Building Blocks TM. Two great tastes that taste great together

Java from a C perspective. Plan

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Transparent Redirection of Network Sockets 1

Comp 204: Computer Systems and Their Implementation. Lecture 12: Scheduling Algorithms cont d

Lecture 6: Semaphores and Monitors

Components of a Reading Workshop Mini-Lesson

Limitations of Data Encapsulation and Abstract Data Types

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

Design Pattern for the Adaptive Scheduling of Real-Time Tasks with Multiple Versions in RTSJ

OPERATING SYSTEMS PROCESS SYNCHRONIZATION

Thread Synchronization and the Java Monitor

As it relates to Android Studio. By Phil Malone:

Unit 6: Conditions, Barriers, and RendezVous

Performance Improvement In Java Application

JVM Tool Interface. Michal Pokorný

Event processing in Java: what happens when you click?

Chapter 1 Java Program Design and Development

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

Lecture 1 Introduction to Android

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

KS3 Computing Group 1 Programme of Study hours per week

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

ODROID Multithreading in Android

Instrumentation Software Profiling

Develop lejos Programs Step by Step

Resurrecting Ada s Rendez-Vous in Java

Java SE 7 Programming

ò Paper reading assigned for next Thursday ò Lab 2 due next Friday ò What is cooperative multitasking? ò What is preemptive multitasking?

Introduction to Object-Oriented Programming

LAB 5: Scheduling Algorithms for Embedded Systems

3D Animation of Java Program Execution for Teaching Object Oriented Concepts

JAVA INTERVIEW QUESTIONS

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Transcription:

Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 1 / 38 Today Some more programming techniques that will be helpful for the assignment. The main subject will be multitasking How to get the robot to do several things at once. That involves using threads. But we ll cover some other useful programming ideas as well. 2 / 38

Why Threads? 3 / 38 Why Threads? 4 / 38

Why Threads? 5 / 38 Threads In robotics we frequently need to deal with concurrency Different bits of code running more or less independently in time. Once upon a time these had to be separate processes. Rather heavyweight. A more modern approach is that of threads These provide fine-grained concurrency within a process. Here we discuss the basic ideas behind the use of threads in Java. 6 / 38

Source This material is drawn from Learning Java, Patrick Niemeyer, Jonathan Knudsen, O Reilly. 7 / 38 What are threads? A thread is a flow of control within a program. Like processes, but threads within a program can easily share state. Threads are like lectures at UoL: Separate entities Share resources Only one entity uses a resource at the same time Need coordination to manage access to resources. Threads also have local data that is distinct. 8 / 38

Thread object All execution in Java is associated with a Thread object. That is what main() launches. New threads are born when a new instance of: java.lang.thread is created This object is what we manipulate to control and coordinate execution of the thread. 9 / 38 Thread object Two ways to handle threads. One way is to sub-class the Thread object. Create your own thread which extends the standard thread. Do this by defining/over-riding the run() method. (This is what is invoked when the thread starts.) Second way is to create a Runnable object and execute it in an unmodified Thread Many Java programmers consider that using Runnable is better style. We will stick to the first. 10 / 38

Scheduling In most Java implementations, threads are time-sliced.??? 11 / 38 Scheduling In most Java implementations, threads are time-sliced. Each one runs for a while in some order (in the implementation that I use, it seems that the first thread to be started is the first one to run). On other Java implementations, you might get different behavior. All depends on what the VM does. All the specification says is as follows (next slide). 12 / 38

Scheduling All threads have a priority value. Any time a higher priority thread becomes runnable, it preempts any lower priority threads and starts executing. By default, threads with the same priority are scheduled round-robin. This means that once a thread begins to run it continues until: It sleeps due to a sleep() or wait(); It waits for the lock for a synchronized method; It blocks on I/O; It explicitly yields control using yield(); or It terminates. So there is no necessity for threads to be time-sliced. 13 / 38 Controlling threads There are a few methods that allow us to control the execution of threads. start() is used to start a thread running. Will see an example in a bit. stop(), suspend() and resume() are deprecated. We will discuss sleep(), wait() and notify(). There are also join() and interrupt(). Won t talk about these. 14 / 38

sleep() Sometimes we need to tell a thread to take a break. The method sleep() will do this. It takes an argument that is the number of milliseconds to sleep for. sleep() is a class method of Thread, so it can be called either using: Thread.sleep() or by calling it on a specific instance of Thread: myownlittlethread.sleep() 15 / 38 sleep() You may have seen this kind of thing: Thread.sleep(200) used without much explanation. Puts the current thread to sleep. Typically the one launched by main(). 16 / 38

sleep() Here s another example from a classic scheduling example: public void run(){ while(true){ System.out.println("One!"); try{ Thread.sleep(1000); catch(interruptedexception e){ // Guess we won t get to sleep after all 17 / 38 sleep() Good practice to put a sleep in a try/catch structure in case the thread is interrupted during its sleep. You often set threads to sleep precisely because you are waiting for them to be interrupted. A sleeping thread can be woken up by an InterruptedException so we need to specify what to do if this happens. 18 / 38

Synchronization When threads share resources, they need to be synchronized Otherwise things can get confusing Imagine two threads trying to use the same variable at the same time. In the lecture example, imagine two lectures trying to use the same classroom at the same time. On a robot, imagine two threads trying to use the same motor at the same time. Even when you take scheduling (in the Java thread sense) into account it can be an issue. Java provides some simple monitor-based methods for controlling access. 19 / 38 Synchronization The most basic idea is that of synchronized methods. Just add the keyword synchronized to the method definition: public synchronized void myfunction(){ : Only one thread at a time is allowed to execute any synchronized method of an object. The object is locked. Other threads are blocked until they can aquire the lock on the object. 20 / 38

Synchronization Note that locks are reentrant, so a thread does not block itself. The synchronized function can call itself recursively, and it can call other synchronized methods of the same object. 21 / 38 wait() and notify() wait() and notify() provide more direct synchronization of threads. When a thread executes a synchronized method that contains a wait(), it gives up its hold on the block and goes to sleep. The idea is that the thread is waiting for some necessary event to take place. Later on, when it wakes up, it will start to try to get the lock for the synchronized object. When it gets the lock, it will continue from where it left off. 22 / 38

wait() and notify() What wakes the thread up from waiting is a call to notify() on the same synchronized object. 23 / 38 Complex huh? Using threads gives you great power to perform complex operations. It also gives you the chance to create really incomprehensible errors. 24 / 38

Back to robots Now, how does this effect robots? 25 / 38 Standard Robot Let s define a Java class to represent our robot. Two touch sensors One ultrasound sensor One colour sensor Two drive motors (I m ignoring the motor pointing the ultrasound sensor). Create an instance as part of a control program. 26 / 38

Standard Robot A data member for each element of the robot. import lejos.nxt.*; import lejos.nxt.addon.colorsensorht; public class StandardRobot{ private TouchSensor leftbump, rightbump; private UltrasonicSensor usense; private ColorHTSensor csense; private NXTRegulatedMotor leftmotor, rightmotor; 27 / 38 Standard Robot Each of these private members would need appropriate get and/or set functions. Get sensor values. Set motor values. Get motor values, for example ismoving() 28 / 38

Standard Robot Constructor sets up the data members to talk to the relevant bits of the hardware. public StandardRobot(){ leftbump = new TouchSensor(SensorPort.S2); rightbump = new TouchSensor(SensorPort.S1); usense = new UltrasonicSensor(SensorPort.S3); csense = new ColorHTSensor(SensorPort.S4); leftmotor = Motor.C; rightmotor = Motor.B; Good Java practice/style to set up the robot like this. Independent of using threads. 29 / 38 Standard Robot Now we ll use a thread to set up a robot monitor. Thread that observes what the robot is doing Uses the StandardRobot object to be able to do this. Reports the robot state on the screen. Useful debug tool. 30 / 38

Standard Robot Set up a thread which can reference a StandardRobot public class RobotMonitor extends Thread{ private int delay; public StandardRobot robot; public RobotMonitor(StandardRobot r, int d){ this.setdaemon(true); delay = d; robot = r; Will explain the daemon bit next. 31 / 38 Daemons Daemons are threads providing services for other threads in the program. They run as background processes They serve basic functionalities upon which other threads build If a thread is declared Daemon, its existence does not prevent the JVM from exiting (unlike other threads). Methods in java.lang.thread: boolean isdaemon() Flags whether thread is daemon void setdaemon (Boolean on) Sets the thread to be a daemon. Can only be used before the thread is created. 32 / 38

Not to be confused with this kind of daemon 33 / 38 Daemons Here our daemon thread reports on the robot: public void run(){ while(true){ LCD.clear(); LCD.drawString(robot.isLeftBumpPressed(), 0, 0); LCD.drawString(robot.isRightBumpPressed(), 0, 1); LCD.drawString(robot.getUSenseRange(), 0, 2); LCD.drawString(robot.getCSenseColor(), 0, 3); try{ sleep(delay); catch(exception e){ // We have no exception handling ; 34 / 38

Standard Robot The functions being called on robot are the get and set functions defined for StandardRobot See the code (on the course website) for details. 35 / 38 Standard Robot Finally we connect the monitor and an instance of StandardRobot public class RunMonitor{ public static void main(string [] args) throws Exception { StandardRobot me = new StandardRobot(); RobotMonitor rm = new RobotMonitor(me, 400); rm.start(); // Here we wait. But could be any control program // either inline, or as an object that is passed // a reference to me (the robot). Button.waitForAnyPress(); 36 / 38

Standard Robot Clearly, we could use the same style to build more complex robot controllers. Threads controlling different aspects of the robot: Moving around Avoiding obstacles Preventing collisions All talking to the StandardRobot object to operate the hardware. All together determining what the robot does. We ll look more into this next time. 37 / 38 Summary This lecture looked at multi-tasking, which is handy for many robotics tasks. First we looked at threads, which provide a lightweight approach to multi-tasking. Then we looked at how threads can be used in LeJOS. Our example also showed how to use LeJOS in a more object-oriented way. 38 / 38