Robotics and Autonomous Systems

Similar documents
THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

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

PROGRAMMING ROBOTS AN ABSTRACT VIEW

Java Threads. COMP 585 Noteset #2 1

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

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

Robotics and Autonomous Systems

COMMUNICATION AND OTHER USEFUL THINGS

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

Animation Part 2: MoveableShape interface & Multithreading

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

Object Oriented Programming. Week 10 Part 1 Threads

CS 556 Distributed Systems

Unit III Rupali Sherekar 2017

7. MULTITHREDED PROGRAMMING

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

Robotics and Autonomous Systems

Robotics and Autonomous Systems

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

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

What is a thread anyway?

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

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

CIS233J Java Programming II. Threads

Concurrent, Real-Time and Distributed Programming in Java

Synchronization synchronization.

G52CON: Concepts of Concurrency

Concurrent Computing CSCI 201 Principles of Software Development

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CS Project 2 - Experience with More lejos Classes

CMSC 330: Organization of Programming Languages

UNIT V CONCURRENT PROGRAMMING

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

Unit - IV Multi-Threading

Multithread Computing

04-Java Multithreading

Techniques of Java Programming: Concurrent Programming in Java

Java Threads. Introduction to Java Threads

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

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

Multithreading Pearson Education, Inc. All rights reserved.

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

JAVA - MULTITHREADING

Multithreaded Programming

Module - 4 Multi-Threaded Programming

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

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

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

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

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Concurrent Programming using Threads

CS 351 Design of Large Programs Threads and Concurrency

CS193k, Stanford Handout #8. Threads 3

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

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

Robotics and Autonomous Systems

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

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

Threads Questions Important Questions

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

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

Advanced Concepts of Programming

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

CSCD 330 Network Programming

CPS221 Lecture: Threads

Synchronization

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

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

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

JAVA. Lab 12 & 13: Multithreading

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

ROBOTICS AND AUTONOMOUS SYSTEMS

Transcription:

1 / 38 Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool

2 / 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.

Why Threads? 3 / 38

Why Threads? 4 / 38

Why Threads? 5 / 38

6 / 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.

Source 7 / 38 This material is drawn from Learning Java, Patrick Niemeyer, Jonathan Knudsen, O Reilly.

8 / 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.

9 / 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.

10 / 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.

11 / 38 Scheduling In most Java implementations, threads are time-sliced.???

12 / 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).

13 / 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.

14 / 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.

sleep() 15 / 38 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()

16 / 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().

17 / 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 } } }

18 / 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.

19 / 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.

20 / 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.

21 / 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.

22 / 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.

wait() and notify() 23 / 38 What wakes the thread up from waiting is a call to notify() on the same synchronized object.

Complex huh? 24 / 38 Using threads gives you great power to perform complex operations. It also gives you the chance to create really incomprehensible errors.

Back to robots 25 / 38 Now, how does this effect robots?

26 / 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.

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

28 / 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()

29 / 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.

30 / 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.

31 / 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.

32 / 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.

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

35 / 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.

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

37 / 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.

38 / 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.