SlideShare a Scribd company logo
THREADS & CONCURRENCY
Lecture 23– CS2110 – Fall 2018
Prelim room assignments (not yet posted
elsewhere)
5:30. URHG01: netids lac326 to rzt4
5:30. BKL200: netids sa2229 to zz632
plus all conflicts moving from 7:30 to 5:30 exam
--------------------------------
7:30. URHG01: aa2277 to gyz2
7:30. BKL200: hcm58 to ky356
plus all conflicts moving from 5:30 to 7:30 exam
There will be a homework on concurrency.
2
CPU Central Processing Unit. Simplified
view
The CPU is the part of the
computer that executes
instructions.
Java: x= x + 2;
Suppose variable x is at
Memory location 800,
Instructions at 10
Machine language:
10: load register 1, 800
11: Add register 1, 2
12: Store register 1, 800
3
Basic uniprocessor-CPU computer.
Black lines indicate data flow, red
lines indicate control flow
From wikipedia
Part of Activity Monitor in Gries’s laptop
4
>100 processes are competing for time. Here’s some of them:
Clock rate
 Clock rate “frequency at which CPU is
running”
Higher the clock rate, the faster
instructions
are executed.
 First CPUs: 5-10 Hz
(cycles per second)
 Today MacBook Pro 3.5GHz
 Your OS can control the
clock rate, slow it down when
idle, speed up when more
5
Why multicore?
 Moore’s Law: Computer speeds and memory
densities nearly double each year
6
But a fast computer runs hot
 Power dissipation rises as square of the clock
rate
 Chips were heading toward melting down!
 Put more CPUs on a chip:
with four CPUs on one
chip, even if we run each at
half speed we can perform
more overall computations!
7
Today: Not one CPU but many
Processing Unit is called a core.
 Modern computers have “multiple cores” (processing
units)
 Instead of a single CPU (central processing unit) on
the chip 5-10 common. Intel has prototypes with 80!
 We often run many programs at the same time
 Even with a single core (processing unit), your program
may have more than one thing “to do” at a time
 Argues for having a way to do many things at once
8
Many programs. Each can have several
“threads of execution”
We often run many programs at the same time
And each program may have several “threads of
execution”
9
Example, in a Paint program,
when you click the pencil tool,
a new thread of execution is
started to call the method to
process it:
Main GUI thread
Process pencil
click
Programming a Cluster...
10
• Sometimes you want to write a
program that is executed on
many machines!
• Atlas Cluster (at Cornell):
• 768 cores
• 1536 GB RAM
• 24 TB Storage
• 96 NICs (Network Interface
Controller)
Programming a Cluster...
11
Programs like those that simulate
weather have a big array of
points,
At each step of simulation,
calculates whether at each point
based on info at surrounding
points.
Each is on a separate processor.
Many processes are executed
simultaneously on your computer
12
• Operating system provides support for multiple
“processes”
• Usually fewer processors than processes
• Processes are an abstraction:
at hardware level, lots of multitasking
–memory subsystem
–video controller
–buses
–instruction prefetching
Concurrency
 Concurrency refers to a single program in which several
processes, called threads, are running simultaneously
 Special problems arise
 They reference the same data and can interfere with
each other, e.g. one process modifies a complex
structure like a heap while another is trying to read it
 CS2110: we focus on two main issues:
 Race conditions
 Deadlock
13
Race conditions
 A “race condition” arises if two or more processes
access the same variables or objects concurrently and
at least one does updates
 Example: Processes t1 and t2 x= x + 1; for some
static global x.
Process t1 Process t2
… ...
x= x + 1; x= x + 1;
But x= x+1; is not an “atomic action”: it takes several steps
14
Race conditions
 LOAD x
 ADD 1
 STORE x
 ...
 LOAD x
 ADD 1
 STORE x
Thread t1 Thread t2
15
 Suppose x is initially 5
 ... after finishing, x = 6! We “lost” an update
Race conditions
 Typical race condition: two processes wanting to change
a stack at the same time. Or make conflicting changes
to a database at the same time.
 Race conditions are bad news
 Race conditions can cause many kinds of bugs, not
just the example we see here!
 Common cause for “blue screens”: null pointer
exceptions, damaged data structures
 Concurrency makes proving programs correct much
harder!
16
Deadlock
 To prevent race conditions, one often requires a process
to “acquire” resources before accessing them, and only
one process can “acquire” a given resource at a time.
 Examples of resources are:
 A file to be read
 An object that maintains a stack, a linked list, a hash
table, etc.
 But if processes have to acquire two or more resources
at the same time in order to do their work, deadlock can
occur. This is the subject of the next slides.
17
Dining philosopher problem
18
Five philosophers
sitting at a table.
Each repeatedly
does this:
1. think
2. eat
What do they
eat?
spaghetti.
Need TWO forks
to eat spaghetti!
Dining philosopher problem
19
Each does
repeatedly :
1. think
2. eat (2 forks)
eat is then:
pick up left fork
pick up right fork
pick up food, eat
put down left fork
put down rght fork
At one point,
they all pick up
their left forks
DEADLOCK!
Dining philosopher problem
20
Simple solution to
deadlock:
Number the forks. Pick
up smaller one first
1. think
2. eat (2 forks)
eat is then:
pick up smaller fork
pick up bigger fork
pick up food, eat
put down bigger fork
put down smallerfork
1
2
4
3
5
Java: What is a Thread?
 A separate “execution” that runs within a single
program and can perform a computational task
independently and concurrently with other threads
 Many applications do their work in just a single thread:
the one that called main() at startup
 But there may still be extra threads...
 ... Garbage collection runs in a “background” thread
 GUIs have a separate thread that listens for events
and “dispatches” calls to methods to process them
 Today: learn to create new threads of our own in Java
21
Thread
 A thread is an object that “independently computes”
 Needs to be created, like any object
 Then “started” --causes some method to be called. It
runs side by side with other threads in the same
program; they see the same global data
 The actual executions could occur on different CPU
cores, but but don’t have to
 We can also simulate threads by multiplexing a
smaller number of cores over a larger number of
threads
22
Java class Thread
 threads are instances of class Thread
 Can create many, but they do consume space & time
 The Java Virtual Machine creates the thread that
executes your main method.
 Threads have a priority
 Higher priority threads are executed preferentially
 By default, newly created threads have initial priority
equal to the thread that created it (but priority can be
changed)
23
Creating a new Thread (Method 1)
24
class PrimeThread extends Thread {
long a, b;
PrimeThread(long a, long b) {
this.a= a; this.b= b;
}
@Override public void run() {
//compute primes between a and b
...
}
}
PrimeThread p= new PrimeThread(143, 195);
p.start();
overrides
Thread.run()
Call run() directly?
no new thread is used:
Calling thread will run it
Do this and
Java invokes run() in new thread
Creating a new Thread (Method 2)
25
class PrimeRun implements Runnable {
long a, b;
PrimeRun(long a, long b) {
this.a= a; this.b= b;
}
public void run() {
//compute primes between a and b
...
}
}
PrimeRun p= new PrimeRun(143, 195);
new Thread(p).start();
Example
26
Thread[Thread-0,5,main] 0
Thread[main,5,main] 0
Thread[main,5,main] 1
Thread[main,5,main] 2
Thread[main,5,main] 3
Thread[main,5,main] 4
Thread[main,5,main] 5
Thread[main,5,main] 6
Thread[main,5,main] 7
Thread[main,5,main] 8
Thread[main,5,main] 9
Thread[Thread-0,5,main] 1
Thread[Thread-0,5,main] 2
Thread[Thread-0,5,main] 3
Thread[Thread-0,5,main] 4
Thread[Thread-0,5,main] 5
Thread[Thread-0,5,main] 6
Thread[Thread-0,5,main] 7
Thread[Thread-0,5,main] 8
Thread[Thread-0,5,main] 9
public class ThreadTest extends Thread {
public static void main(String[] args) {
new ThreadTest().start();
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}
}
public void run() {
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}
}
}
Thread name, priority, thread group
Example
27 Thread[main,5,main] 0
Thread[main,5,main] 1
Thread[main,5,main] 2
Thread[main,5,main] 3
Thread[main,5,main] 4
Thread[main,5,main] 5
Thread[main,5,main] 6
Thread[main,5,main] 7
Thread[main,5,main] 8
Thread[main,5,main] 9
Thread[Thread-0,4,main] 0
Thread[Thread-0,4,main] 1
Thread[Thread-0,4,main] 2
Thread[Thread-0,4,main] 3
Thread[Thread-0,4,main] 4
Thread[Thread-0,4,main] 5
Thread[Thread-0,4,main] 6
Thread[Thread-0,4,main] 7
Thread[Thread-0,4,main] 8
Thread[Thread-0,4,main] 9
public class ThreadTest extends Thread {
public static void main(String[] args) {
new ThreadTest().start();
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}
}
public void run() {
currentThread().setPriority(4);
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}
}
}
Thread name, priority, thread group
Example
28 Thread[main,5,main] 0
Thread[main,5,main] 1
Thread[main,5,main] 2
Thread[main,5,main] 3
Thread[main,5,main] 4
Thread[main,5,main] 5
Thread[Thread-0,6,main] 0
Thread[Thread-0,6,main] 1
Thread[Thread-0,6,main] 2
Thread[Thread-0,6,main] 3
Thread[Thread-0,6,main] 4
Thread[Thread-0,6,main] 5
Thread[Thread-0,6,main] 6
Thread[Thread-0,6,main] 7
Thread[Thread-0,6,main] 8
Thread[Thread-0,6,main] 9
Thread[main,5,main] 6
Thread[main,5,main] 7
Thread[main,5,main] 8
Thread[main,5,main] 9
public class ThreadTest extends Thread {
public static void main(String[] args) {
new ThreadTest().start();
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}
}
public void run() {
currentThread().setPriority(6);
for (int i= 0; i < 10; i++) {
System.out.format("%s %dn",
Thread.currentThread(), i);
}}}
Thread name, priority, thread group
Example
29
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
waiting...
running...
done
public class ThreadTest extends Thread {
static boolean ok = true;
public static void main(String[] args) {
new ThreadTest().start();
for (int i = 0; i < 10; i++) {
System.out.println("waiting...");
yield();
}
ok = false;
}
public void run() {
while (ok) {
System.out.println("running...");
yield();
}
System.out.println("done");
}
}
If threads happen to be sharing
a CPU, yield allows other waiting
threads to run.
Terminating Threads is tricky
 Easily done... but only in certain ways
 Safe way to terminate a thread: return from method
run
 Thread throws uncaught exception? whole program
will be halted (but it can take a second or two ... )
 Some old APIs have issues: stop(), interrupt(),
suspend(),
destroy(), etc.
 Issue: Can easily leave application in a “broken”
internal state.
 Many applications have some kind of variable telling
the thread to stop itself.
30
Threads can pause
 When active, a thread is “runnable”.
 It may not actually be “running”. For that, a CPU
must schedule it. Higher priority threads could run
first.
 A thread can pause
 Call Thread.sleep(k) to sleep for k milliseconds
 Doing I/O (e.g. read file, wait for mouse input, open
file) can cause thread to pause
 Java has a form of locks associated with objects.
When threads lock an object, one succeeds at a time.
31
Background (daemon) Threads
 In many applications we have a notion of “foreground”
and “background” (daemon) threads
 Foreground threads are doing visible work, like
interacting with the user or updating the display
 Background threads do things like maintaining data
structures (rebalancing trees, garbage collection, etc.)
 On your computer, the same notion of background
workers explains why so many things are always
running in the task manager.
32
Fancier forms of locking
 Java developers have created various synchronization
abstract data types
 Semaphores: a kind of synchronized counter
(invented by Dijkstra)
 Event-driven synchronization
 The Windows and Linux and Apple O/S have kernel
locking features, like file locking
 But for Java, synchronized is the core mechanism
33
Summary
 Use of multiple processes and multiple threads within
each process can exploit concurrency
 Which may be real (multicore) or “virtual” (an
illusion)
 When using threads, beware!
 Synchronize any shared memory to avoid race
conditions
 Synchronize objects in certain order to avoid
deadlocks
 Even with proper synchronization, concurrent
programs can have other problems such as
“livelock”
 Serious treatment of concurrency is a complex topic
34

More Related Content

Similar to cs2110Concurrency1.ppt

Introduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clustersIntroduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clusters
Sri Prasanna
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using AutomataModeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Daniel Bristot de Oliveira
 
concurrency
concurrencyconcurrency
concurrency
Jonathan Wagoner
 
OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switch
Daniel Ben-Zvi
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ganesh Samarthyam
 
Concurrent programming with RTOS
Concurrent programming with RTOSConcurrent programming with RTOS
Concurrent programming with RTOS
Sirin Software
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Easier, Better, Faster, Safer Deployment with Docker and Immutable Containers
Easier, Better, Faster, Safer Deployment with Docker and Immutable ContainersEasier, Better, Faster, Safer Deployment with Docker and Immutable Containers
Easier, Better, Faster, Safer Deployment with Docker and Immutable Containers
C4Media
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Threads v3
Threads v3Threads v3
Threads v3
Sunil OS
 
Python multithreading
Python multithreadingPython multithreading
Slot02 concurrency1
Slot02 concurrency1Slot02 concurrency1
Slot02 concurrency1
Viên Mai
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
Daniel Blezek
 

Similar to cs2110Concurrency1.ppt (20)

Introduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clustersIntroduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clusters
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using AutomataModeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
 
concurrency
concurrencyconcurrency
concurrency
 
OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switch
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Concurrent programming with RTOS
Concurrent programming with RTOSConcurrent programming with RTOS
Concurrent programming with RTOS
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Easier, Better, Faster, Safer Deployment with Docker and Immutable Containers
Easier, Better, Faster, Safer Deployment with Docker and Immutable ContainersEasier, Better, Faster, Safer Deployment with Docker and Immutable Containers
Easier, Better, Faster, Safer Deployment with Docker and Immutable Containers
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
Threads v3
Threads v3Threads v3
Threads v3
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Slot02 concurrency1
Slot02 concurrency1Slot02 concurrency1
Slot02 concurrency1
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 

Recently uploaded

2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
IJECEIAES
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 

Recently uploaded (20)

2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...An improved modulation technique suitable for a three level flying capacitor ...
An improved modulation technique suitable for a three level flying capacitor ...
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 

cs2110Concurrency1.ppt

  • 1. THREADS & CONCURRENCY Lecture 23– CS2110 – Fall 2018
  • 2. Prelim room assignments (not yet posted elsewhere) 5:30. URHG01: netids lac326 to rzt4 5:30. BKL200: netids sa2229 to zz632 plus all conflicts moving from 7:30 to 5:30 exam -------------------------------- 7:30. URHG01: aa2277 to gyz2 7:30. BKL200: hcm58 to ky356 plus all conflicts moving from 5:30 to 7:30 exam There will be a homework on concurrency. 2
  • 3. CPU Central Processing Unit. Simplified view The CPU is the part of the computer that executes instructions. Java: x= x + 2; Suppose variable x is at Memory location 800, Instructions at 10 Machine language: 10: load register 1, 800 11: Add register 1, 2 12: Store register 1, 800 3 Basic uniprocessor-CPU computer. Black lines indicate data flow, red lines indicate control flow From wikipedia
  • 4. Part of Activity Monitor in Gries’s laptop 4 >100 processes are competing for time. Here’s some of them:
  • 5. Clock rate  Clock rate “frequency at which CPU is running” Higher the clock rate, the faster instructions are executed.  First CPUs: 5-10 Hz (cycles per second)  Today MacBook Pro 3.5GHz  Your OS can control the clock rate, slow it down when idle, speed up when more 5
  • 6. Why multicore?  Moore’s Law: Computer speeds and memory densities nearly double each year 6
  • 7. But a fast computer runs hot  Power dissipation rises as square of the clock rate  Chips were heading toward melting down!  Put more CPUs on a chip: with four CPUs on one chip, even if we run each at half speed we can perform more overall computations! 7
  • 8. Today: Not one CPU but many Processing Unit is called a core.  Modern computers have “multiple cores” (processing units)  Instead of a single CPU (central processing unit) on the chip 5-10 common. Intel has prototypes with 80!  We often run many programs at the same time  Even with a single core (processing unit), your program may have more than one thing “to do” at a time  Argues for having a way to do many things at once 8
  • 9. Many programs. Each can have several “threads of execution” We often run many programs at the same time And each program may have several “threads of execution” 9 Example, in a Paint program, when you click the pencil tool, a new thread of execution is started to call the method to process it: Main GUI thread Process pencil click
  • 10. Programming a Cluster... 10 • Sometimes you want to write a program that is executed on many machines! • Atlas Cluster (at Cornell): • 768 cores • 1536 GB RAM • 24 TB Storage • 96 NICs (Network Interface Controller)
  • 11. Programming a Cluster... 11 Programs like those that simulate weather have a big array of points, At each step of simulation, calculates whether at each point based on info at surrounding points. Each is on a separate processor.
  • 12. Many processes are executed simultaneously on your computer 12 • Operating system provides support for multiple “processes” • Usually fewer processors than processes • Processes are an abstraction: at hardware level, lots of multitasking –memory subsystem –video controller –buses –instruction prefetching
  • 13. Concurrency  Concurrency refers to a single program in which several processes, called threads, are running simultaneously  Special problems arise  They reference the same data and can interfere with each other, e.g. one process modifies a complex structure like a heap while another is trying to read it  CS2110: we focus on two main issues:  Race conditions  Deadlock 13
  • 14. Race conditions  A “race condition” arises if two or more processes access the same variables or objects concurrently and at least one does updates  Example: Processes t1 and t2 x= x + 1; for some static global x. Process t1 Process t2 … ... x= x + 1; x= x + 1; But x= x+1; is not an “atomic action”: it takes several steps 14
  • 15. Race conditions  LOAD x  ADD 1  STORE x  ...  LOAD x  ADD 1  STORE x Thread t1 Thread t2 15  Suppose x is initially 5  ... after finishing, x = 6! We “lost” an update
  • 16. Race conditions  Typical race condition: two processes wanting to change a stack at the same time. Or make conflicting changes to a database at the same time.  Race conditions are bad news  Race conditions can cause many kinds of bugs, not just the example we see here!  Common cause for “blue screens”: null pointer exceptions, damaged data structures  Concurrency makes proving programs correct much harder! 16
  • 17. Deadlock  To prevent race conditions, one often requires a process to “acquire” resources before accessing them, and only one process can “acquire” a given resource at a time.  Examples of resources are:  A file to be read  An object that maintains a stack, a linked list, a hash table, etc.  But if processes have to acquire two or more resources at the same time in order to do their work, deadlock can occur. This is the subject of the next slides. 17
  • 18. Dining philosopher problem 18 Five philosophers sitting at a table. Each repeatedly does this: 1. think 2. eat What do they eat? spaghetti. Need TWO forks to eat spaghetti!
  • 19. Dining philosopher problem 19 Each does repeatedly : 1. think 2. eat (2 forks) eat is then: pick up left fork pick up right fork pick up food, eat put down left fork put down rght fork At one point, they all pick up their left forks DEADLOCK!
  • 20. Dining philosopher problem 20 Simple solution to deadlock: Number the forks. Pick up smaller one first 1. think 2. eat (2 forks) eat is then: pick up smaller fork pick up bigger fork pick up food, eat put down bigger fork put down smallerfork 1 2 4 3 5
  • 21. Java: What is a Thread?  A separate “execution” that runs within a single program and can perform a computational task independently and concurrently with other threads  Many applications do their work in just a single thread: the one that called main() at startup  But there may still be extra threads...  ... Garbage collection runs in a “background” thread  GUIs have a separate thread that listens for events and “dispatches” calls to methods to process them  Today: learn to create new threads of our own in Java 21
  • 22. Thread  A thread is an object that “independently computes”  Needs to be created, like any object  Then “started” --causes some method to be called. It runs side by side with other threads in the same program; they see the same global data  The actual executions could occur on different CPU cores, but but don’t have to  We can also simulate threads by multiplexing a smaller number of cores over a larger number of threads 22
  • 23. Java class Thread  threads are instances of class Thread  Can create many, but they do consume space & time  The Java Virtual Machine creates the thread that executes your main method.  Threads have a priority  Higher priority threads are executed preferentially  By default, newly created threads have initial priority equal to the thread that created it (but priority can be changed) 23
  • 24. Creating a new Thread (Method 1) 24 class PrimeThread extends Thread { long a, b; PrimeThread(long a, long b) { this.a= a; this.b= b; } @Override public void run() { //compute primes between a and b ... } } PrimeThread p= new PrimeThread(143, 195); p.start(); overrides Thread.run() Call run() directly? no new thread is used: Calling thread will run it Do this and Java invokes run() in new thread
  • 25. Creating a new Thread (Method 2) 25 class PrimeRun implements Runnable { long a, b; PrimeRun(long a, long b) { this.a= a; this.b= b; } public void run() { //compute primes between a and b ... } } PrimeRun p= new PrimeRun(143, 195); new Thread(p).start();
  • 26. Example 26 Thread[Thread-0,5,main] 0 Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 Thread[Thread-0,5,main] 1 Thread[Thread-0,5,main] 2 Thread[Thread-0,5,main] 3 Thread[Thread-0,5,main] 4 Thread[Thread-0,5,main] 5 Thread[Thread-0,5,main] 6 Thread[Thread-0,5,main] 7 Thread[Thread-0,5,main] 8 Thread[Thread-0,5,main] 9 public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); } } public void run() { for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); } } } Thread name, priority, thread group
  • 27. Example 27 Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 Thread[Thread-0,4,main] 0 Thread[Thread-0,4,main] 1 Thread[Thread-0,4,main] 2 Thread[Thread-0,4,main] 3 Thread[Thread-0,4,main] 4 Thread[Thread-0,4,main] 5 Thread[Thread-0,4,main] 6 Thread[Thread-0,4,main] 7 Thread[Thread-0,4,main] 8 Thread[Thread-0,4,main] 9 public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); } } public void run() { currentThread().setPriority(4); for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); } } } Thread name, priority, thread group
  • 28. Example 28 Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[Thread-0,6,main] 0 Thread[Thread-0,6,main] 1 Thread[Thread-0,6,main] 2 Thread[Thread-0,6,main] 3 Thread[Thread-0,6,main] 4 Thread[Thread-0,6,main] 5 Thread[Thread-0,6,main] 6 Thread[Thread-0,6,main] 7 Thread[Thread-0,6,main] 8 Thread[Thread-0,6,main] 9 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); } } public void run() { currentThread().setPriority(6); for (int i= 0; i < 10; i++) { System.out.format("%s %dn", Thread.currentThread(), i); }}} Thread name, priority, thread group
  • 29. Example 29 waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... done public class ThreadTest extends Thread { static boolean ok = true; public static void main(String[] args) { new ThreadTest().start(); for (int i = 0; i < 10; i++) { System.out.println("waiting..."); yield(); } ok = false; } public void run() { while (ok) { System.out.println("running..."); yield(); } System.out.println("done"); } } If threads happen to be sharing a CPU, yield allows other waiting threads to run.
  • 30. Terminating Threads is tricky  Easily done... but only in certain ways  Safe way to terminate a thread: return from method run  Thread throws uncaught exception? whole program will be halted (but it can take a second or two ... )  Some old APIs have issues: stop(), interrupt(), suspend(), destroy(), etc.  Issue: Can easily leave application in a “broken” internal state.  Many applications have some kind of variable telling the thread to stop itself. 30
  • 31. Threads can pause  When active, a thread is “runnable”.  It may not actually be “running”. For that, a CPU must schedule it. Higher priority threads could run first.  A thread can pause  Call Thread.sleep(k) to sleep for k milliseconds  Doing I/O (e.g. read file, wait for mouse input, open file) can cause thread to pause  Java has a form of locks associated with objects. When threads lock an object, one succeeds at a time. 31
  • 32. Background (daemon) Threads  In many applications we have a notion of “foreground” and “background” (daemon) threads  Foreground threads are doing visible work, like interacting with the user or updating the display  Background threads do things like maintaining data structures (rebalancing trees, garbage collection, etc.)  On your computer, the same notion of background workers explains why so many things are always running in the task manager. 32
  • 33. Fancier forms of locking  Java developers have created various synchronization abstract data types  Semaphores: a kind of synchronized counter (invented by Dijkstra)  Event-driven synchronization  The Windows and Linux and Apple O/S have kernel locking features, like file locking  But for Java, synchronized is the core mechanism 33
  • 34. Summary  Use of multiple processes and multiple threads within each process can exploit concurrency  Which may be real (multicore) or “virtual” (an illusion)  When using threads, beware!  Synchronize any shared memory to avoid race conditions  Synchronize objects in certain order to avoid deadlocks  Even with proper synchronization, concurrent programs can have other problems such as “livelock”  Serious treatment of concurrency is a complex topic 34