THREADS AND MULTITASKING ROBOTS

Similar documents
ROBOTICS AND AUTONOMOUS SYSTEMS

Robotics and Autonomous Systems

PROGRAMMING ROBOTS AN ABSTRACT VIEW

Java Threads. COMP 585 Noteset #2 1

COMMUNICATION AND OTHER USEFUL THINGS

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Robotics and Autonomous Systems

Java Threads. Written by John Bell for CS 342, Spring 2018

Object Oriented Programming. Week 10 Part 1 Threads

LEJOS AND JASON ROBOTICS AND AUTONOMOUS SYSTEMS. Today. Today we will just go through an example of how to interface. Department of Computer Science

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Today. Robotics and Autonomous Systems. The scenario (again) Basic control loop

CMSC 132: Object-Oriented Programming II. Threads in Java

Today. Robotics and Autonomous Systems. Today. Communication on the NXT. Lecture 14: Communication and other useful things.

Animation Part 2: MoveableShape interface & Multithreading

CS 556 Distributed Systems

Unit III Rupali Sherekar 2017

7. MULTITHREDED PROGRAMMING

Robotics and Autonomous Systems

Robotics and Autonomous Systems

Programming Language Concepts: Lecture 11

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Java s Implementation of Concurrency, and how to use it in our applications.

Threads Chate Patanothai

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Note: Each loop has 5 iterations in the ThreeLoopTest program.

What is a thread anyway?

Multi-threading in Java. Jeff HUANG

CSCD 330 Network Programming

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Synchronization synchronization.

Concurrent, Real-Time and Distributed Programming in Java

CIS233J Java Programming II. Threads

G52CON: Concepts of Concurrency

Concurrent Computing CSCI 201 Principles of Software Development

CS Project 2 - Experience with More lejos Classes

CMSC 330: Organization of Programming Languages

UNIT V CONCURRENT PROGRAMMING

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Today. Robotics and Autonomous Systems. Jason and LeJOS. Jason and LeJOS. Lecture 23: LeJOS and Jason. Richard Williams

CSCD 330 Network Programming

CS360 Lecture 10 Multithreading

Contents. 6-1 Copyright (c) N. Afshartous

Multithreaded Programming

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Unit - IV Multi-Threading

Multithread Computing

04-Java Multithreading

Techniques of Java Programming: Concurrent Programming in Java

Java Threads. Introduction to Java Threads

ROBOTICS AND AUTONOMOUS SYSTEMS

Object Oriented Programming (II-Year CSE II-Sem-R09)

Multithreading Pearson Education, Inc. All rights reserved.

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

JAVA - MULTITHREADING

Multithreaded Programming

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Module - 4 Multi-Threaded Programming

Navigation and path execution NAVIGATION IN LEJOS ROBOTICS AND AUTONOMOUS SYSTEMS. Today. Digging into the detail of how you do the last two.

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Threads in Java (Deitel & Deitel)

Software Practice 1 - Multithreading

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Advanced Concepts of Programming

CS 351 Design of Large Programs Threads and Concurrency

CS193k, Stanford Handout #8. Threads 3

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Robotics and Autonomous Systems

By: Abhishek Khare (SVIM - INDORE M.P)

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Multithreading in Java Part 2 Thread - States JAVA9S.com

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Threads Questions Important Questions

Concurrent Programming using Threads

CS360 Lecture 12 Multithreading

THREADS AND CONCURRENCY

User Space Multithreading. Computer Science, University of Warwick

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.

Introduction to Java Threads

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Lecture 9: Introduction to Monitors

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Synchronization

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

ECE 462 Object-Oriented Programming using C++ and Java. Scheduling and Critical Section

JAVA. Lab 12 & 13: Multithreading

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Synchronization in Java

Multi-threaded programming in Java

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Transcription:

ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 comp329-2013-parsons-lect10 2/37 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. THREADS AND MULTITASKING ROBOTS comp329-2013-parsons-lect10 3/37 Why Threads?

comp329-2013-parsons-lect10 4/37 Why Threads? comp329-2013-parsons-lect10 6/37 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. comp329-2013-parsons-lect10 5/37 Why Threads? comp329-2013-parsons-lect10 7/37 This material is drawn from Learning Java, Patrick Niemeyer, Jonathan Knudsen, O Reilly.

comp329-2013-parsons-lect10 8/37 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. comp329-2013-parsons-lect10 10/37 One way to handle threads 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. Many Java programmers consider that using Runnable is better style. We won t cover that. comp329-2013-parsons-lect10 9/37 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. comp329-2013-parsons-lect10 11/37 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.

comp329-2013-parsons-lect10 12/37 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. comp329-2013-parsons-lect10 14/37 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() comp329-2013-parsons-lect10 13/37 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. comp329-2013-parsons-lect10 15/37 You may have seen this: Thread.sleep(200) used without much explanation. Puts the current thread to sleep. Typically the one launched by main().

comp329-2013-parsons-lect10 16/37 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 comp329-2013-parsons-lect10 18/37 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 our class example, imagine two classes trying to use the same classroom 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. comp329-2013-parsons-lect10 17/37 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. comp329-2013-parsons-lect10 19/37 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.

comp329-2013-parsons-lect10 20/37 Note that locks are reentrant, so a thread does not block itself. It can call itself recursively, and it can call other synchronized methods of the same object. comp329-2013-parsons-lect10 22/37 What wakes the thread up from waiting is a call to notify() on the same synchronized object. comp329-2013-parsons-lect10 21/37 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 tread 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. comp329-2013-parsons-lect10 23/37 Complex huh? Using threads gives you great power to perform complex operations. It also gives you the chance to create really incomprehensible errors.

comp329-2013-parsons-lect10 24/37 Now, how does this effect robots? comp329-2013-parsons-lect10 26/37 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; comp329-2013-parsons-lect10 25/37 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. comp329-2013-parsons-lect10 27/37 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()

comp329-2013-parsons-lect10 28/37 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. comp329-2013-parsons-lect10 30/37 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; comp329-2013-parsons-lect10 29/37 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. comp329-2013-parsons-lect10 31/37 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.

comp329-2013-parsons-lect10 32/37 Not to be confused with comp329-2013-parsons-lect10 34/37 The functions being called on robot are the get and set functions defined for StandardRobot See the code (on the course website) for details. comp329-2013-parsons-lect10 33/37 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 ; comp329-2013-parsons-lect10 35/37 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();

comp329-2013-parsons-lect10 36/37 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. comp329-2013-parsons-lect10 37/37 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.