Programação Usando Threads em C - dcc.ufmg.br · Threads em C. O que são Threads?
04 threads-pbl-2-slots
-
Upload
mha4 -
Category
Engineering
-
view
211 -
download
0
Transcript of 04 threads-pbl-2-slots
Titile
Lecture 04Chapter 7: Threads
(35 slides- 2 slots)
Why should you study this chapter?This chapter will help you developing a program in which some tasks executing concurrently. Nowadays, in one program, some tasks execute concurrently. You usually saw them in a web page including texts, sounds, images, games, changing concurrently.Nowadays, operating systems (OS) support many programs running concurrently.Open the Task Manager of Windows OS (Ctrl Alt Delete) to see how many programs are running in your computer.2
ReviewPrevious lecture:Introduction to OO ParadigmBenefits of OO ImplementationHints for class designDeclaring/ Using classes/ abstract classes/ Interfaces/ Anonymous classes/ Enum types3
ObjectivesDefinitions: Process, thread.Multi-Processing System and Multi-Threading Program.What are threads.Thread Fundamentals in JavaMonitors, Waiting and Notifying
Your homework: Workshop 3 (with report): The producer-consumer problem and the philosophers problem.Workshop 4 (with report): Deadlock application. Refer to the source code in the page 236 of the book Complete Java 2 Certification. Explain why the application causes deadlock.Assessment: the next class.4
1- DefinitionsProgram-chng trnh: An executable file (data + code) stored in secondary memory(disk).Process- tin trnh: A program in running. Its data and code are loaded to RAM in a contiguous memory block.Thread- lung: is a smallest unit code (function/method) in an application that performs a special job. An application can contain some threads. A thread can be called as lightweight process.
DataCode
Thread 1Thread 2Thread 35
7.1- Processes and Multi Processing SystemA process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.Multi Processing/ Multi Tasking System: Almost of operating systems allows many processes executing concurrently. Open the Task Manager of Windows OS ( Ctrl+Alt+Del) to see current processes in your computer.Applications tag contains processes which you start them.Processes tag contains processes which automatically run immediately after the startup of OS. 6
How can OS manage concurrent processesMemoryApp1CodeDataApp2CodeDataApp3CodeData
AppCode AddrDuration(mili sec)CPUApp110320151App240154172App380166221
Process Table maintains information of processes. How does OS manage executions of processes?Time-slicing mechanism. Each process is allocated resources ( CPU, ) for executing in a time-slot (such as 30 milliseconds). When the time duration expires, this process will pause to yield resources to the next process which will be chosen by the scheduler of OS. 7
7.2- Threads and Multi-ThreadingThreads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process every process has at least one thread (main thread). Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.Multithreaded execution is an essential feature of the Java platform. Threads in a program are managed by the JVM.8
How can JVM manage threadsMemory of a multi-thread processAppData
Code of thread1Code of thread2Code of thread3
Thread is a smallest unit code in an application that performs a special job. A program can have several threads they can be executed concurrently. ThreadCode AddrDuration(mili sec)CPUStateThread 110320151readyThread 240154172readyThread 380166221sleep.
Thread Table maintains information of threads Time-slicing mechanism is used to schedule thread executions also. 9
Difference:MemoryApp1DataCodeApp2DataCodeApp3DataCodeMemoryApp1dataCode
Code of thread1Code of thread2Code of thread3
10
Race ConditionsApplicationData 1 (shared data)Data 2Data 3Thread 1Thread 2Thread3Thread 4
A raceoccursNeedSynchronizationSuppose that Thread2 and Thread4 concurrently execute.TimeThread 2Thread41Data1=102.3.Data1= 1004.56Y= Data1;7
Y=?11
Synchronize ng(cng) b(bc chn). Bn cht ca s ng b l ch nhau. Trong tin hc, ng b mt nhm tac v l cng bc cc tc v ny phi thc thi tun t (khng cho php thc thi ng thi). Giao tip ng b l giao tip ch c mt ngi ni ti mt thi im (khi phng vn, giao tip hnh thc). Giao tip khng ng b l giao tip mi ngi u c th ni ng thi (khi ci ln). 11
7.3- Thread Fundamentals in JavaThreading supports in Java:The java.lang.Thread classThe java.lang.Object classThe Java language and JVM ( Java Virtual Machine)How to create a thread in Java?Create a subclass of the java.lang.Thread class and override the method run()Create a class implementing the Runnable interface and override the run() method.12
ThreadCode AddrStatemain8000runt10320run
Create a subclass of the Thread class
Thread tableEvery process has at least one thread (main thread).
?The start() method is implemented in the Thread class. This method calls the method run(). This process has 2 threads running concurrently. At a time, order of their execution is decided by the scheduler.13
Class implements the Runnable interface
ThreadCode AddrStatemain8000runt10320run
14
The java.lang.Thread classConstructorThread() Thread(Runnabletarget) Thread(Runnabletarget, Stringname) Thread(Stringname)Thread(ThreadGroupgroup, Runnabletarget)Thread(ThreadGroupgroup, Runnabletarget, Stringname)Thread(ThreadGroupgroup, Runnabletarget, Stringname, longstackSize) Thread(ThreadGroupgroup, Stringname)
Declarationpublic class Thread extends Object implements Runnable
Common Methodsstart()join ()sleep (milisec)yield()notify()notifyAll()wait()
PropertiesidnamestatethreadGroupdaemonpriority
set/get-is
15
join(): kt hp Lung hin hnh s chy cho n khi lung kt thcyield(): nhng Lung hin hnh ch ng tm ngng, nhng CPU cho lung khcnotify(): Cnh bo Lung hin hnh giao tip vi JVM, yu cu JVM cho lung u hng i ready khi lp lch, lung ny s c thc thi. Hnh vi notify() thng c dng ngay sau hnh vi wait() JVM modifies thread tablenotifyAll(): cnh bo tt c Lung hin hnh yu cu JVM cho tt c cc lung trong hng JVM modifies thread table
15
Using some methods of the Thread class
16
Thread StatesRunningBlockedSleepingSuspendedReadyMonitorStates(JVM)yield() start()(Scheduler)sleep(milisec)Time expired or interruptedBlocking method(IO)Blocking condition changes or interruptwait()notify()Ready: As soon as it is created , it can enter the running state when JVMs processor is assigned to it.Running: It get full attention of JVMs processor which executes the threads run() methodDead: When the run() method terminates.Interrupt: A signal is sent to CPU from IO device just after an IO operation has terminated. Only ready threads will be chosen by the JVM scheduler at a time.17
Non-race DemonstrationThis program contains 2 threads: The first thread that will print out the system time for every second. The second will print out the sum of two random integers for every half of a second.
18
Non-race Demonstration
19
7.4- Monitors, Waiting and NotifyingSome threads can access common resources concurrently. We must synchronize accessing common resources Every object has a lockLock: an extra variable is added by the compiler for monitoring the state of common resource. Before a thread accesses the common resource, the lock is tested. After a thread has the lock (it is permitted to access the common resource), it can access common resource. When it did, it needs notifying to others thread ( wait-notify mechanism). RunningSeeking LockwaitingReadySchedulerwait()notify(), notifyAll(), time out, or interruptEnter synchronized codeLock obtained20
Monitors, Waiting and NotifyingTwo ways to mark code as synchronize Synchronize an entire method: Let the synchronized modifier in the methods declaration. synchronized Type Method(args){ }Synchronize some method of an object Type Method ( args){ synchronized ( object_var){ object_var.method1(args); object_var.method2(args); } }A class contains synchronized code is called monitor.Monitor: A technique to encapsulate common resources to a class. When a thread wants to access common resources, it must call a public synchronized method. As a result, common resources are accessed in successive manner.21
Demo:The Producer-Consumer ProblemProducer makes a product then puts it to a store.Consumer buys a product from a store.Selling Procedure: First In First Out
Attention!: Store is common resource of 2 threads: producer and consumer. Store is a monitor and its activities needs synchronization Synchronizing: * After a thread accessed common resource, it should sleep a moment or it must notify to the next thread ( or all thread) in the thread-pool to awake and execute.* Use the synchronized keyword to declare a method that will access common resource.ProducerConsumer
productproductPut to the tailGet from the headStore22
The Producer-Consumer Problem
/* synchronized */No synchronizationA product is simulated as a number.23
The Producer-Consumer Problem
24
The Producer-Consumer Problem
25
The Producer-Consumer Problem
Synchronization is not usedSynchronization is used:26
7.5- DeadlockWhat is deadlock?Deadlock describes a situation where two or more threads are blocked forever, waiting for each other All threads in a group halt.When does deadlock occur? There exists a circular wait the lock that is held by other thread.
Nothing can ensure that DEADLOCK do not occur.27
Deadlock Demo.
28
The Philosophers Problem
Wait-NotifyMechanism, a way helps preventing deadlocks3 classesDeadlock!29
The Philosophers Problem
ThreadCode AddrDuration(mili sec)CPUStateThread 110320151Suspended ReadyThread 240154172SuspendedThread 380166221Suspended.
Thread pool30
The Philosophers Problem
31
The Philosophers Problem
32
SummaryConcepts were introduced:Definitions: Program, Process, ThreadMulti-processing systemMulti-threading programming in JavaThread Fundamentals in JavaSynchronizing access to common resource.Monitoring thread states: Wait-notify mechanism.If you want some tasks executing concurrently, multi-threading is a solution.33
ExercisesWorkshop 3 (with report): The producer-consumer problem and the philosophers problem.Workshop 4 (with report): Deadlock application. Refer to the source code in the page 236 of the book Complete Java 2 Certification. Explain why the application causes deadlock.
34
Thank You
35