32
Visual basic 2005 Visual basic 2005 IX. MULTITHREADING MELJUN CORTES MELJUN CORTES

MELJUN CORTES

Embed Size (px)

Citation preview

Page 1: MELJUN CORTES

Visual basic 2005Visual basic 2005IX. MULTITHREADING

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES

MultithreadingMultithreadingObjectives

MULTITHREADING 2

Visual Basic 2005

In this chapter you will learn:•What threads are and why they are useful.•How threads enable you to implement and manage concurrent activities.•The life cycle of a thread.•Thread priorities and scheduling.•To create and execute Threads.•Thread synchronization.•What producer/consumer relationships are and how they are implemented with multithreading.•To ensure that the User Interface thread performs all GUI modifications that are initiated by other threads in a Windows application.

Page 3: MELJUN CORTES

OverviewOverview

It would be nice if we could perform one action at a time and perform it well

The human body performs a great variety of operations in parallel or concurrently

Ironically, most programming languages do not enable programmers to specify concurrent activities

Rather, programming languages generally provide only a simple set of control statements that enable programmers to perform one action at a time

3MULTITHREADING

Visual Basic 2005

Multithreading

Page 4: MELJUN CORTES

OverviewOverview

The FCL provides concurrency primitivesMultithreading is the ability of an

application to contain "threads of execution," each of which designates a portion of a program that may execute concurrently with other threads

Multithreading is available to all .NET programming languages

The FCL's multithreading capabilities are located in the System.Threading namespace

4MULTITHREADING

Visual Basic 2005

Multithreading

Page 5: MELJUN CORTES

Life Cycle of a ThreadLife Cycle of a Thread

At any time, a thread is said to be in one of several thread states

Two classes critical for multithreaded applications are Thread and Monitor, both of the System.Threading namespace

5MULTITHREADING

Visual Basic 2005

Multithreading

Page 6: MELJUN CORTES

Life Cycle of a ThreadLife Cycle of a Thread

Thread life cycle in UML state diagram:

6MULTITHREADING

Visual Basic 2005

Multithreading

Unstarted

Running

SuspendedWaitSleepJoin Stopped BlockedStart

Pulse, PulseAll, Interrupt

Sleep interval expires

Wait, Sleep, JoinRe

sume

Susp

end

Abort

CompleteLock available,

I/O completion

Lock unavailable,

Issue I/O request

Page 7: MELJUN CORTES

Life Cycle of a ThreadLife Cycle of a Thread

A Thread object begins its life cycle in the Unstarted state

The thread remains in the Unstarted state until the Thread's Start method is called, which places the thread in the Running state

A Running thread enters the Stopped (or Aborted) state when its ThreadStart delegate terminates

7MULTITHREADING

Visual Basic 2005

Multithreading

Page 8: MELJUN CORTES

Life Cycle of a ThreadLife Cycle of a Thread

A thread is considered to be Blocked if it is unable to use a processor, even if one is available

There are three ways in which a Running thread enters the WaitSleepJoin state:◦The thread can call Monitor method Wait◦The thread can call Thread method Sleep ◦The thread can call Thread method Join

8MULTITHREADING

Visual Basic 2005

Multithreading

Page 9: MELJUN CORTES

Life Cycle of a ThreadLife Cycle of a Thread

If a Running Thread's Suspend method is called, the Running thread enters the Suspended state

A Suspended thread returns to the Running state when another thread in the program invokes the Suspended Thread's Resume method

9MULTITHREADING

Visual Basic 2005

Multithreading

Page 10: MELJUN CORTES

Thread Priorities and Thread Thread Priorities and Thread SchedulingScheduling

Every thread has a priority in the range between ThreadPriority.Lowest and ThreadPriority.Highest

These values come from the ThreadPriority enumeration (namespace System.Threading):◦Lowest◦BelowNormal◦Normal◦AboveNormal ◦Highest

10MULTITHREADING

Visual Basic 2005

Multithreading

Page 11: MELJUN CORTES

Thread Priorities and Thread Thread Priorities and Thread SchedulingScheduling

The Windows operating system supports a concept called timeslicing that enables threads of equal priority to share a processor

With timeslicing, each thread receives a brief burst of processor time, called a quantum, during which the thread can execute

MULTITHREADING 11

Visual Basic 2005

Multithreading

Page 12: MELJUN CORTES

Thread Priorities and Thread Thread Priorities and Thread SchedulingScheduling

The job of the thread scheduler is to keep the highest-priority thread running at all times

And also, to ensure that all such threads execute for a quantum in round-robin fashion

MULTITHREADING 12

Visual Basic 2005

Multithreading

Page 13: MELJUN CORTES

Thread Priorities and Thread Thread Priorities and Thread SchedulingScheduling

Thread-priority scheduling, mulitlevel priority queue

MULTITHREADING 13

Priority Highest

Priority AboveNormal

Priority Normal

Priority BelowNormal

Priority Lowest

A B

C

D E F

G

Ready threads

Visual Basic 2005

Multithreading

Page 14: MELJUN CORTES

Creating and Executing ThreadsCreating and Executing Threads

To create a thread, we can use the following declaration:

MULTITHREADING 14

Dim thread1 As New Thread(New ThreadStart(AddressOf Class1.method))

thread1 object variable

Thread class ThreadStart delegate

AddressOf keyword

Method to execute in the thread

Visual Basic 2005

Multithreading

Page 15: MELJUN CORTES

Creating and Executing ThreadsCreating and Executing Threads

Threads sleeping and printing

MULTITHREADING 15

Imports System.Threading

Module ModThreadTester

Sub Main() ' Create and name each thread. Use MessagePrinter's ' Print method as argument to ThreadStart delegate. Dim printer1 As New MessagePrinter Dim thread1 As New Thread(New ThreadStart(AddressOf printer1.Print)) thread1.Name = "thread1"

Dim printer2 As New MessagePrinter Dim thread2 As New Thread(New ThreadStart(AddressOf printer2.Print)) thread2.Name = "thread2“

Dim printer3 As New MessagePrinter Dim thread3 As New Thread(New ThreadStart(AddressOf printer3.Print)) thread3.Name = "thread3“

. . .continued

Visual Basic 2005

Multithreading

Page 16: MELJUN CORTES

Creating and Executing ThreadsCreating and Executing Threads

Threads sleeping and printing

MULTITHREADING 16

Console.WriteLine("Starting threads in Main")

' call each thread's Start method to place each ' thread in Running state thread1.Start() thread2.Start() thread3.Start()

Console.WriteLine("Threads started, Main ends" & vbCrLf) Console.Read() End Sub

. . .continued

Visual Basic 2005

Multithreading

Page 17: MELJUN CORTES

Creating and Executing ThreadsCreating and Executing Threads

Threads sleeping and printing

MULTITHREADING 17

Class MessagePrinter ' Print method of this class used to control threads Private sleepTime As Integer Private Shared random As New Random

' constructor to initialize a MessagePrinter object Sub New() ' pick random sleep time between 0 and 5 seconds sleepTime = random.Next(5001) End Sub ' New

' method Print controls thread that prints messages Public Sub Print() ' obtain reference to currently executing thread Dim current As Thread = Thread.CurrentThread

Console.WriteLine(current.Name & " going to sleep for " & _ sleepTime & " milliseconds") Thread.Sleep(sleepTime) ' sleep for sleepTime milliseconds

' display the thread's name Console.WriteLine(current.Name + " done sleeping") End Sub ' Print End Class ' MessagePrinterEnd Module

Visual Basic 2005

Multithreading

Page 18: MELJUN CORTES

Creating and Executing ThreadsCreating and Executing Threads

Threads sleeping and printing

MULTITHREADING 18

Visual Basic 2005

Multithreading

Page 19: MELJUN CORTES

Thread Synchronization and Class Thread Synchronization and Class MonitorMonitor

Often, multiple threads of execution manipulate shared data

If threads with access to shared data simply read that data, then any number of threads can access the data simultaneously without problems

However, when multiple threads share data and the data is modified by one or more of the threads, then indeterminate results may occur

MULTITHREADING 19

Visual Basic 2005

Multithreading

Page 20: MELJUN CORTES

Thread Synchronization and Class Thread Synchronization and Class MonitorMonitor

The problem can be solved by giving one thread at a time exclusive access to code that manipulates the shared data

During this time, other threads wishing to manipulate the data are kept waiting

When the thread with exclusive access to the data completes its data manipulations, one of the waiting threads is allowed to proceed

MULTITHREADING 20

Visual Basic 2005

Multithreading

Page 21: MELJUN CORTES

Thread Synchronization and Class Thread Synchronization and Class MonitorMonitor

Each thread accessing the shared data excludes all other threads from doing so simultaneously, this is called mutual exclusion or thread synchronization

Visual Basic programmers use the .NET Framework's monitors to perform synchronization

MULTITHREADING 21

Visual Basic 2005

Multithreading

Page 22: MELJUN CORTES

Thread Synchronization and Class Thread Synchronization and Class MonitorMonitor

Class Monitor provides the methods for locking objects to implement synchronized access to shared data

Locking an object means that only one thread can access that object at a time

When a thread wishes to acquire exclusive control over an object, the thread invokes the Monitor method Enter to acquire the lock on the data object

MULTITHREADING 22

Visual Basic 2005

Multithreading

Page 23: MELJUN CORTES

Thread Synchronization and Class Thread Synchronization and Class MonitorMonitor

Visual Basic provides another means of manipulating an object's lock, the SyncLock statement

MULTITHREADING 23

SyncLock objectReference ' code that requires synchronization goes here End SyncLock

The objectReference is the same reference that normally would be

passed to Monitor methods Enter, Exit, Pulse and PulseAll

Visual Basic 2005

Multithreading

Page 24: MELJUN CORTES

Producer/Consumer Relationship Producer/Consumer Relationship without Thread Synchronizationwithout Thread Synchronization

The producer portion of an application generates data

the consumer portion of the application uses that data

A producer thread calls a produce method to generate data and place it in a shared region of memory called a buffer

MULTITHREADING 24

Visual Basic 2005

Multithreading

Page 25: MELJUN CORTES

Producer/Consumer Relationship Producer/Consumer Relationship without Thread Synchronizationwithout Thread Synchronization

A consumer thread calls a consume method to read the data

If the producer wishes to put the next data in the buffer but determines that the consumer has not yet read the previous data from the buffer, the producer thread should call Wait

MULTITHREADING 25

Visual Basic 2005

Multithreading

Page 26: MELJUN CORTES

Producer/Consumer Relationship Producer/Consumer Relationship without Thread Synchronizationwithout Thread Synchronization

MULTITHREADING 26

Producer

Consumer

Buffer

data

data

Visual Basic 2005

Multithreading

Page 27: MELJUN CORTES

Producer/Consumer Relationship Producer/Consumer Relationship without Thread Synchronizationwithout Thread Synchronization

MULTITHREADING 27

Producer produces 1 and stores to buffer 1

Consumer consumes 1 and retrieves from buffer

Producer produces 2 and stores to buffer

Producer produces 3 and stores to buffer

2

3

Consumer consumes 3 and retrieves from buffer

Producer produces 4 and stores to buffer 4

Producer produces 5 and stores to buffer 5

Consumer consumes 5 and retrieves from buffer

Consumer still consumes 5 and retrieves from buffer 5

Buffer

Visual Basic 2005

Multithreading

Page 28: MELJUN CORTES

Producer/Consumer Relationship with Producer/Consumer Relationship with Thread SynchronizationThread Synchronization

MULTITHREADING 28

Producer produces 1 and stores to buffer 1

Producer tries to write. Buffer full, Producer waits 1

Consumer consumes 1 and retrieves from buffer

Buffer

1

Occupied Count

1

Producer produces 2 and stores to buffer 2 1

1 0

Consumer consumes 2 and retrieves from buffer 2 0

Producer produces 3 and stores to buffer 3 1

Producer tries to write. Buffer full, Producer waits 3 1

Consumer consumes 3 and retrieves from buffer 3 0

Visual Basic 2005

Multithreading

Page 29: MELJUN CORTES

Producer/Consumer Relationship: Producer/Consumer Relationship: Circular BufferCircular Buffer

There are too many interactions that occur with the operating system, the network, the user and other components, which can cause the threads to operate at different speeds

When threads wait, programs can become less productive, user-interactive programs can become less responsive and network applications can suffer longer delays because the processor is not used efficiently

MULTITHREADING 29

Visual Basic 2005

Multithreading

Page 30: MELJUN CORTES

Producer/Consumer Relationship: Producer/Consumer Relationship: Circular BufferCircular Buffer

To minimize the waiting for threads that share resources and operate at the same relative speeds, we can implement a circular buffer

This provides extra locations in which the producer can place values (if it "gets ahead" of the consumer) and from which the consumer can retrieve those values (while it is "catching up" to the producer)

MULTITHREADING 30

Visual Basic 2005

Multithreading

Page 31: MELJUN CORTES

Producer/Consumer Relationship: Producer/Consumer Relationship: Circular BufferCircular Buffer

MULTITHREADING 31

All buffers empty, Consumer waits -1

Buffers

0

Occupied Count

-1 -1

Producer produces 1 and stores to buffer 1 1-1 -1

Consumer consumes 1 and retrieves from buffer 1 0-1 -1

Producer produces 2 and stores to buffer 1 12 -1

Consumer consumes 2 and retrieves from buffer 1 02 -1

Producer produces 3 and stores to buffer 1 12 3

Producer produces 4 and stores to buffer 4 22 3

Producer produces 5 and stores to buffer 4 35 3

Consumer consumes 3 and retrieves from buffer 4 25 6

Visual Basic 2005

Multithreading

Page 32: MELJUN CORTES

End of MultithreadingEnd of MultithreadingMULTITHREADING 32

Visual Basic 2005

Multithreading