SlideShare uma empresa Scribd logo
1 de 50
Threads
Cesarano Antonio
Del Monte Bonaventura
Università degli studi di
Salerno
7th April 2014
Operating Systems II
Agenda
 Introduction
 Threads models
 Multithreading: single-core Vs multicore
 Implementation
 A Case Study
 Conclusions
CPU Trends
Introduction
What’s a Thread?
Memory: Heavy vs Light processes
Introduction
Why should I care about Threads?
 Pro
• Responsiveness
• Resources
sharing
• Economy
• Scalability
Cons
• Hard implementation
• Synchronization
• Critical section,
deadlock, livelock…
Introduction
Thread Models
Two kinds of Threads
User Threads Kernel Threads
Thread Models
User-level Threads
Implemented in software library
 Pthread
 Win32 API
Pro:
• Easy handling
• Fast context switch
• Trasparent to OS
• No new address
space, no need to
change address
space
Cons:
• Do not benefit from
multithreading or
multiprocessing
• Thread blocked
Process blocked
Thread Models
Kernel-level
Threads Executed only in kernel mode, managed
by OS
 Kthreadd children
Pro:
• Resource Aware
• No need to use a
new address space
• Thread blocked
Scheduled
Con:
• Slower then User-
threads
Thread Models
Thread implementation models:
From many to one
From one to one
From many to many
Thread Models
From many to one
 Whole process is blocked if one thread is
blocked
 Useless on multicore architectures
Thread Models
From one to one
 Works fine on multicore architectures
o Many kernel threads = High overhead
Thread Models
From many to many
 Works fine on multicore architectures
 Less overhead then “one to one” model
Multithreading
Multitasking
Single core Symmetric
Multi-Processor
MultiThreading
Multithreading
Multithreading
HyperThreadin
g
Multithreading
 How can We use multithreading
architectures?
Thread
Level
Parallelism
Data
Level
Parallelis
m
Multithreading
Thread Level Parallelism
Multithreading
Data Level Parallelism
Multithreading
Granularity
 Coarse-
grained:
Multithreading
 Context switch on high latency event
 Very fast thread-switching, no threads slow down
 Loss of throughput due to short stalls: pipeline start-
up
Granularity
 Fine-grained
Multithreading
 Context switch on every cycle
 Interleaved execution of multiple threads: it can
hide
both short and long stalls
 Rarely-stalling threads are slowed down
Granularity
Multithreading
Context Switching
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 1regs
Thread
2
registers
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Running Ready
Pushing old context
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 1regs
Thread 2
registers
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Thread 1
registers
Running Ready
Saving old stack pointer
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 1regs
Thread 2
registers
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Thread 1
registers
Running Ready
Changing stack pointer
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 1regs
Thread 2
registers
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Thread 1
registers
Ready Running
Popping off thread #2 old
context
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 2 regs
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Thread 1
registers
Ready Running
Done: return
Single-core Vs Multi-core
Xthread_ctxtswitc
h:
pusha
movl esp, [eax]
movl edx, esp
popa
ret
CPU
ESP
Thread 2 regs
Thread 1 TCB
SP: ....
Thread 2 TCB
SP: ....
Thread 1
registers
Ready Running
RET pops of the
returning address
and it assigns its
value to PC reg
Problems
 Critical Section:
When a thread A tries to access to a shared
variable simultaneously to a thread B
 Deadlock:
When a process A is waiting for
resource reserved to B, which is
waiting for resource reserved to A
 Race Condition:
The result of an execution depens on
the order of execution of different
threads
More Issues
 fork() and exec() system calls: to duplicate or
to not deplicate all threads?
 Signal handling in multithreading application.
 Scheduler activation: kernel threads have to
communicate with user thread, i.e.: upcalls
 Thread cancellation: termination a thread
before it has completed.
• Deferred cancellation
• Asynchronous cancellation: immediate
Designing a thread library
 Multiprocessor support
 Virtual processor
 RealTime support
 Memory Management
 Provide functions library rather than a module
 Portability
 No Kernel mode
Implementation
Posix Thread
 Posix standard for threads: IEEE POSIX
1003.1c
 Library made up of a set of types and
procedure calls written in C, for UNIX
platform
 It supports:
a) Thread management
b) Mutexes
c) Condition Variables
d) Synchronization between threads using
R/W locks and barries
Implementation
Thread Pool
 Different threads available in a pool
 When a task arrives, it gets assigned to a
free thread
 Once a thread completes its service, it
returns in the pool and awaits another work.
Implementation
PThred Lib base operations
 pthread_create()- create and launch a new thread
 pthread_exit()- destroy a running thread
 pthread_attr_init()- set thread attributes to their
default values
 pthread_join()- the caller thread blocks and waits
for another thread to finish
 pthread_self()- it retrieves the id assigned to the
calling thread
Implementation Example
N x N Matrix Multiplication
Implementation Example
A simple algorithm
for (int i = 0; i < MATRIX_ELEMENTS; i += MATRIX_LINE)
{
for (int j = 0; j < MATRIX_LINE; ++j)
{
float tmp = 0;
for (int k = 0; k < MATRIX_LINE; k++)
{
tmp +=
A[i + k] * B[(MATRIX_LINE * k) + j];
}
C[i + j] = tmp;
}
}
Implementation Example
SIMD Approach
transpose(B);
for (int i = 0; i < MATRIX_LINE; i++) {
for (int j = 0; j < MATRIX_LINE; j++){
__m128 tmp = _mm_setzero_ps();
for (int k = 0; k < MATRIX_LINE; k += 4){
tmp = _mm_add_ps(tmp,
_mm_mul_ps(_mm_load_ps(&A[MATRIX_LINE * i + k]),
_mm_load_ps(&B[MATRIX_LINE * j +
k])));
}
tmp = _mm_hadd_ps(tmp, tmp);
tmp = _mm_hadd_ps(tmp, tmp);
_mm_store_ss(&C[MATRIX_LINE * i + j], tmp);
}
}
transpose(B);
Implementation Example
TLP Approach
struct thread_params
{
pthread_t id;
float* a;
float* b;
float* c;
int low;
int high;
bool flag;
};
………
int main(int argc, char** argv){
int
ncores=sysconf(_SC_NPROCESSORS_ONLN);
int stride = MATRIX_LINE / ncores;
for (int j = 0; j < ncores; ++j){
pthread_attr_t attr;
pthread_attr_init(&attr);
thread_params* par = new
thread_params;
par->low=j*stride; par-
>high=j*stride+stride;
par->a = A; par->b = B; par->c = C;
pthread_create(&(par->id), &attr, runner,
par);
// set cpu affinity for thread
// sched_setaffinity
}
Implementation Example
TLP Approach
int main(int argc, char**
argv){
….
int completed = 0;
while (true) {
if (completed >= ncores)
break;
completed = 0;
usleep(100000);
for (int j=0; j<ncores;
++j){
if (p[j]->flag)
completed++;
}
}
….
}
void runner(void* p){
thread_params* params = (thread_params*)
p;
int low = params->low; // unpack others
values
for (int i = low; i < high; i++) {
for (int j = 0; j < MATRIX_LINE; j++)
{
float tmp = 0;
for (int k = 0; k < MATRIX_LINE; k++){
tmp +=
A[MATRIX_LINE * i + k] *
B[(MATRIX_LINE * k) + j];
}
C[i + j] = tmp;
}
}
Implementation Performance
0
500
1000
1500
2000
2500
3000
3500
4000
4500
5000
5500
6000
6500
7000
7500
8000
8500
9000
Simple SIMD TLP SIMD&TLP
8 cores
4 cores
A case study
Using threads in Interactive Systems
• Research by XEROX PARC Palo Alto
• Analysis of two large interactive system: Cedar and GVX
• Goals:
i. Identifing paradigms of thread usage
ii. architecture analysis of thread-based environment
iii. pointing out the most important properties of an
interactive system
A case study
Thread model
 Mesa language
 Multiple, lightweight, pre-emptively scheduled threads in shared
address space, threads may have different priorities
 FORK, JOIN, DETACH
 Support to conditional variables and monitors: critical sections and
mutexes
 Finer grain for locks: directly on data structures
A case study
Three types of thread
1. Eternal: run forever, waiting for cond. var.
2. Worker: perform some computation
3. Transient: short life threads, forked off by long-lived
threads
A case study
Dynamic analysis
0
5
10
15
20
25
30
35
40
45
Cedar GVX
# threads idle
Fork rate max
# threads max
Switching intervals: (130/sec, 270/sec) vs. (33/sec,
60/sec)
A case study
Paradigms of thread usage
 Defer Work: forking for reducing latency
 print documents
 Pumps or slack processes: components of pipeline
 Preprocessing user input
 Request to X server
 Sleepers and one-shots: wait for some event and then
execute
 Blink cursor
 Double click
 Deadlock avoiders: avoid violating lock order constraint
 Windows repainting
A case study
Paradigms of thread usage
 Task rejuvenation: recover a service from a bad state,
either forking a new thread or reporting the error
o Avoid fork overhead in input event dispatcher of
Cedar
 Serializers: thread processing a queue
o A window system with input events from many
sources
 Concurrency exploiters: for using multiple processors
 Encapsulated forks: a mix of previous paradigms, code
modularity
A case study
Common Mistakes and Issues
o Timeout hacks for compensate missing NOTIFY
o IF instead of WHILE for monitors
o Handling resources consumption
o Slack processes may need hack YieldButNotToMe
o Using single-thread designed libraries in multi-
threading environment: Xlib and XI
o Spurious lock
A case study
Xerox scientists’ conclusions
 Interesting difficulties were discovered both in
use and implementation of multi-threading
environment
 Starting point for new studies
Conclusion

Mais conteúdo relacionado

Mais procurados

Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating Systems
Nitish Gulati
 

Mais procurados (20)

Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Distributed Operating System_1
Distributed Operating System_1Distributed Operating System_1
Distributed Operating System_1
 
Parallel processing
Parallel processingParallel processing
Parallel processing
 
Threads ppt
Threads pptThreads ppt
Threads ppt
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Memory models
Memory modelsMemory models
Memory models
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess Communication
 
cpu scheduling
cpu schedulingcpu scheduling
cpu scheduling
 
Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Context switching
Context switchingContext switching
Context switching
 
Heterogeneous computing
Heterogeneous computingHeterogeneous computing
Heterogeneous computing
 
Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating Systems
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Interface in java
Interface in javaInterface in java
Interface in java
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 

Semelhante a Threads and multi threading

Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
Aravindharamanan S
 
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
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
babayaga920391
 

Semelhante a Threads and multi threading (20)

Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
 
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
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
 
Threads
ThreadsThreads
Threads
 
Os
OsOs
Os
 
Chapter 6 os
Chapter 6 osChapter 6 os
Chapter 6 os
 
Network Programming: Data Plane Development Kit (DPDK)
Network Programming: Data Plane Development Kit (DPDK)Network Programming: Data Plane Development Kit (DPDK)
Network Programming: Data Plane Development Kit (DPDK)
 
A22 Introduction to DTrace by Kyle Hailey
A22 Introduction to DTrace by Kyle HaileyA22 Introduction to DTrace by Kyle Hailey
A22 Introduction to DTrace by Kyle Hailey
 
Operating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - ThreadsOperating Systems 1 (7/12) - Threads
Operating Systems 1 (7/12) - Threads
 
CH04.pdf
CH04.pdfCH04.pdf
CH04.pdf
 
Bglrsession4
Bglrsession4Bglrsession4
Bglrsession4
 
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
 
Sucet os module_2_notes
Sucet os module_2_notesSucet os module_2_notes
Sucet os module_2_notes
 
Fast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating SystemsFast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating Systems
 
Data race
Data raceData race
Data race
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 

Mais de Antonio Cesarano

Mais de Antonio Cesarano (8)

Inspire JSON Merger
Inspire JSON MergerInspire JSON Merger
Inspire JSON Merger
 
Erasmus Traineeship Report @ RedHat
Erasmus Traineeship Report @ RedHatErasmus Traineeship Report @ RedHat
Erasmus Traineeship Report @ RedHat
 
Lost John - Mobile Game Development
Lost John - Mobile Game DevelopmentLost John - Mobile Game Development
Lost John - Mobile Game Development
 
Pitch ItLosers - TechGarage 2014
Pitch ItLosers - TechGarage 2014Pitch ItLosers - TechGarage 2014
Pitch ItLosers - TechGarage 2014
 
Project Proposal - Project Management
Project Proposal - Project ManagementProject Proposal - Project Management
Project Proposal - Project Management
 
Project management - Final Report
Project management - Final ReportProject management - Final Report
Project management - Final Report
 
Tech Talk Project Work
Tech Talk Project WorkTech Talk Project Work
Tech Talk Project Work
 
Cluster based storage - Nasd and Google file system - advanced operating syst...
Cluster based storage - Nasd and Google file system - advanced operating syst...Cluster based storage - Nasd and Google file system - advanced operating syst...
Cluster based storage - Nasd and Google file system - advanced operating syst...
 

Último

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 

Threads and multi threading

  • 1. Threads Cesarano Antonio Del Monte Bonaventura Università degli studi di Salerno 7th April 2014 Operating Systems II
  • 2. Agenda  Introduction  Threads models  Multithreading: single-core Vs multicore  Implementation  A Case Study  Conclusions
  • 5. Memory: Heavy vs Light processes Introduction
  • 6. Why should I care about Threads?  Pro • Responsiveness • Resources sharing • Economy • Scalability Cons • Hard implementation • Synchronization • Critical section, deadlock, livelock… Introduction
  • 7. Thread Models Two kinds of Threads User Threads Kernel Threads
  • 8. Thread Models User-level Threads Implemented in software library  Pthread  Win32 API Pro: • Easy handling • Fast context switch • Trasparent to OS • No new address space, no need to change address space Cons: • Do not benefit from multithreading or multiprocessing • Thread blocked Process blocked
  • 9. Thread Models Kernel-level Threads Executed only in kernel mode, managed by OS  Kthreadd children Pro: • Resource Aware • No need to use a new address space • Thread blocked Scheduled Con: • Slower then User- threads
  • 10. Thread Models Thread implementation models: From many to one From one to one From many to many
  • 11. Thread Models From many to one  Whole process is blocked if one thread is blocked  Useless on multicore architectures
  • 12. Thread Models From one to one  Works fine on multicore architectures o Many kernel threads = High overhead
  • 13. Thread Models From many to many  Works fine on multicore architectures  Less overhead then “one to one” model
  • 18.  How can We use multithreading architectures? Thread Level Parallelism Data Level Parallelis m Multithreading
  • 21. Granularity  Coarse- grained: Multithreading  Context switch on high latency event  Very fast thread-switching, no threads slow down  Loss of throughput due to short stalls: pipeline start- up
  • 22. Granularity  Fine-grained Multithreading  Context switch on every cycle  Interleaved execution of multiple threads: it can hide both short and long stalls  Rarely-stalling threads are slowed down
  • 24. Context Switching Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 1regs Thread 2 registers Thread 1 TCB SP: .... Thread 2 TCB SP: .... Running Ready
  • 25. Pushing old context Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 1regs Thread 2 registers Thread 1 TCB SP: .... Thread 2 TCB SP: .... Thread 1 registers Running Ready
  • 26. Saving old stack pointer Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 1regs Thread 2 registers Thread 1 TCB SP: .... Thread 2 TCB SP: .... Thread 1 registers Running Ready
  • 27. Changing stack pointer Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 1regs Thread 2 registers Thread 1 TCB SP: .... Thread 2 TCB SP: .... Thread 1 registers Ready Running
  • 28. Popping off thread #2 old context Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 2 regs Thread 1 TCB SP: .... Thread 2 TCB SP: .... Thread 1 registers Ready Running
  • 29. Done: return Single-core Vs Multi-core Xthread_ctxtswitc h: pusha movl esp, [eax] movl edx, esp popa ret CPU ESP Thread 2 regs Thread 1 TCB SP: .... Thread 2 TCB SP: .... Thread 1 registers Ready Running RET pops of the returning address and it assigns its value to PC reg
  • 30. Problems  Critical Section: When a thread A tries to access to a shared variable simultaneously to a thread B  Deadlock: When a process A is waiting for resource reserved to B, which is waiting for resource reserved to A  Race Condition: The result of an execution depens on the order of execution of different threads
  • 31. More Issues  fork() and exec() system calls: to duplicate or to not deplicate all threads?  Signal handling in multithreading application.  Scheduler activation: kernel threads have to communicate with user thread, i.e.: upcalls  Thread cancellation: termination a thread before it has completed. • Deferred cancellation • Asynchronous cancellation: immediate
  • 32. Designing a thread library  Multiprocessor support  Virtual processor  RealTime support  Memory Management  Provide functions library rather than a module  Portability  No Kernel mode
  • 33. Implementation Posix Thread  Posix standard for threads: IEEE POSIX 1003.1c  Library made up of a set of types and procedure calls written in C, for UNIX platform  It supports: a) Thread management b) Mutexes c) Condition Variables d) Synchronization between threads using R/W locks and barries
  • 34. Implementation Thread Pool  Different threads available in a pool  When a task arrives, it gets assigned to a free thread  Once a thread completes its service, it returns in the pool and awaits another work.
  • 35. Implementation PThred Lib base operations  pthread_create()- create and launch a new thread  pthread_exit()- destroy a running thread  pthread_attr_init()- set thread attributes to their default values  pthread_join()- the caller thread blocks and waits for another thread to finish  pthread_self()- it retrieves the id assigned to the calling thread
  • 36. Implementation Example N x N Matrix Multiplication
  • 37. Implementation Example A simple algorithm for (int i = 0; i < MATRIX_ELEMENTS; i += MATRIX_LINE) { for (int j = 0; j < MATRIX_LINE; ++j) { float tmp = 0; for (int k = 0; k < MATRIX_LINE; k++) { tmp += A[i + k] * B[(MATRIX_LINE * k) + j]; } C[i + j] = tmp; } }
  • 38. Implementation Example SIMD Approach transpose(B); for (int i = 0; i < MATRIX_LINE; i++) { for (int j = 0; j < MATRIX_LINE; j++){ __m128 tmp = _mm_setzero_ps(); for (int k = 0; k < MATRIX_LINE; k += 4){ tmp = _mm_add_ps(tmp, _mm_mul_ps(_mm_load_ps(&A[MATRIX_LINE * i + k]), _mm_load_ps(&B[MATRIX_LINE * j + k]))); } tmp = _mm_hadd_ps(tmp, tmp); tmp = _mm_hadd_ps(tmp, tmp); _mm_store_ss(&C[MATRIX_LINE * i + j], tmp); } } transpose(B);
  • 39. Implementation Example TLP Approach struct thread_params { pthread_t id; float* a; float* b; float* c; int low; int high; bool flag; }; ……… int main(int argc, char** argv){ int ncores=sysconf(_SC_NPROCESSORS_ONLN); int stride = MATRIX_LINE / ncores; for (int j = 0; j < ncores; ++j){ pthread_attr_t attr; pthread_attr_init(&attr); thread_params* par = new thread_params; par->low=j*stride; par- >high=j*stride+stride; par->a = A; par->b = B; par->c = C; pthread_create(&(par->id), &attr, runner, par); // set cpu affinity for thread // sched_setaffinity }
  • 40. Implementation Example TLP Approach int main(int argc, char** argv){ …. int completed = 0; while (true) { if (completed >= ncores) break; completed = 0; usleep(100000); for (int j=0; j<ncores; ++j){ if (p[j]->flag) completed++; } } …. } void runner(void* p){ thread_params* params = (thread_params*) p; int low = params->low; // unpack others values for (int i = low; i < high; i++) { for (int j = 0; j < MATRIX_LINE; j++) { float tmp = 0; for (int k = 0; k < MATRIX_LINE; k++){ tmp += A[MATRIX_LINE * i + k] * B[(MATRIX_LINE * k) + j]; } C[i + j] = tmp; } }
  • 42. A case study Using threads in Interactive Systems • Research by XEROX PARC Palo Alto • Analysis of two large interactive system: Cedar and GVX • Goals: i. Identifing paradigms of thread usage ii. architecture analysis of thread-based environment iii. pointing out the most important properties of an interactive system
  • 43. A case study Thread model  Mesa language  Multiple, lightweight, pre-emptively scheduled threads in shared address space, threads may have different priorities  FORK, JOIN, DETACH  Support to conditional variables and monitors: critical sections and mutexes  Finer grain for locks: directly on data structures
  • 44. A case study Three types of thread 1. Eternal: run forever, waiting for cond. var. 2. Worker: perform some computation 3. Transient: short life threads, forked off by long-lived threads
  • 45. A case study Dynamic analysis 0 5 10 15 20 25 30 35 40 45 Cedar GVX # threads idle Fork rate max # threads max Switching intervals: (130/sec, 270/sec) vs. (33/sec, 60/sec)
  • 46. A case study Paradigms of thread usage  Defer Work: forking for reducing latency  print documents  Pumps or slack processes: components of pipeline  Preprocessing user input  Request to X server  Sleepers and one-shots: wait for some event and then execute  Blink cursor  Double click  Deadlock avoiders: avoid violating lock order constraint  Windows repainting
  • 47. A case study Paradigms of thread usage  Task rejuvenation: recover a service from a bad state, either forking a new thread or reporting the error o Avoid fork overhead in input event dispatcher of Cedar  Serializers: thread processing a queue o A window system with input events from many sources  Concurrency exploiters: for using multiple processors  Encapsulated forks: a mix of previous paradigms, code modularity
  • 48. A case study Common Mistakes and Issues o Timeout hacks for compensate missing NOTIFY o IF instead of WHILE for monitors o Handling resources consumption o Slack processes may need hack YieldButNotToMe o Using single-thread designed libraries in multi- threading environment: Xlib and XI o Spurious lock
  • 49. A case study Xerox scientists’ conclusions  Interesting difficulties were discovered both in use and implementation of multi-threading environment  Starting point for new studies