SlideShare una empresa de Scribd logo
1 de 50
Introduction to POSIX Threads Asynchronous Programming in a Unix/Linux Environment Doug Abbott Silver City, NM 575-388-4879 email:  [email_address] web:  www. Intellimetrix.us Class #308
Topics ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Interrupt Mainline Instruction Execution “ Event” Interrupt Service Routine
Interrupts Cause Problems Thread 1 Thread 2 Data Structure while (1) { wait for (event1); write (data_structure); } while (1) { wait for (event2); read (data_structure); } Priority 1 Priority 2
The Real-time Programming Problem Thread 2 while (1) { Reading data structure;   INTERRUPT (event 1)! Still reading data structure; (but data has changed!) } Thread 1 executes!
Multitasking is... ,[object Object],[object Object],[object Object]
“ Processes” vs “Threads” DATA CODE DATA CODE DATA CODE UNIX Process Model DATA THREAD 1 THREAD 2 THREAD 3 Multi-threaded Process
Creating a Linux Process--the  fork()  function ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thread API int pthread_create (pthread_t *thread, pthread_attr_t *attr, void *(* start_ routine) (void *), void *arg); void pthread_exit (void *retval); int pthread_join (pthread_t thread, void **thread_return); pthread_t pthread_self (void); int sched_yield (void);
/*  Thread Example  */ #include <pthread.h> #include &quot;errors.h&quot; /* * Thread start routine. */ void *thread_routine (void *arg) { printf (&quot;%s&quot;), arg); return arg; } main (int argc, char *argv[]) { pthread_t thread_id; void *thread_result; int status; status = pthread_create (&thread_id, NULL, thread_routine, (void *)argv[0]); printf (&quot;New thread created&quot;); status = pthread_join (thread_id, thread_result); printf (&quot;Thread returned %p&quot;, thread_result); return 0; }
Thread State Diagram Ready Blocked Running Terminated created scheduled preempted wait for resource wait satisfied done or cancelled
Thread Termination ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Attribute Objects ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thread Attributes ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
/*  Thread Attributes  */ #include <limits.h> #include <pthread.h> void *thread_routine (void *arg) {/ * Thread start routine. Reports it ran, and then exits. */ printf (&quot;The thread is here&quot;); return NULL; } int main (int argc, char *argv[]) { pthread_t thread_id; pthread_attr_t thread_attr; size_t stack_size; int status; status = pthread_attr_init (&thread_attr); status = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); #ifdef _POSIX_THREAD_ATTR_STACKSIZE / *  Set stack size to twice the minimum  */ status = pthread_attr_getstacksize (&thread_attr, &stack_size); printf (&quot;Default stack size is %u; minimum is %u&quot;, stack_size, PTHREAD_STACK_MIN); status = pthread_attr_setstacksize (&thread_attr, PTHREAD_STACK_MIN*2); #endif status = pthread_create (&thread_id, &thread_attr, thread_routine, NULL); printf (&quot;Main exiting&quot;); return 0; }
Thread Scheduling int pthread_attr_setschedparam (pthread_attr_t *attr, const struct sched_param *param); int pthread_attr_getschedparam (const pthread_attr_t *attr, struct sched_param *param); int pthread_attr_setschedpolicy (pthread_attr_t *attr, int policy); int pthread_attr_getschedpolicy (const pthread_attr_t *attr, int *policy); int pthread_attr_setinheritsched (pthread_attr_t *attr, int inherit); int pthread_attr_getinheritsched (const pthread_attr_t *attr, int *inherit); int pthread_setschedparam (pthread_t pthread, int *policy,    const struct sched_param *param); int pthread_getschedparam (pthread_t pthread, int *policy,  struct sched_param *param); int sched_get_priority_max (int policy); int sched_get_priority_min (int policy); Optional Thread Attributes
Scheduling Policies ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Scheduling: Non-Preemptive vs Preemptive ISR Task Hi Task Lo Blocks Interrupt Ready ISR Task Hi Task Lo NON-PREEMPTIVE PREEMPTIVE Ready
Reentrancy & “Thread-safe” Functions ,[object Object],[object Object],[object Object]
return addr Reentrancy--What is it void fun1 (int a, int b) { int i, j; i = a; j = b; . . } b a i j stack pointer Stack “frame” for fun1 Stack
return addr A Non-reentrant Function int j; void fun2 (int a, int b) { int i; i = a; j = b; if (j == 0) { } } b a i Stack sp j Heap
Sharing Resources Thread 1 Thread 2 “ I am Thread 1” “ I am Thread 2” “ II a amm  ThThrreeadad  12” Code in Thread n printf (“I am Thread %d”, n);
Sharing Resources with a Mutex Thread 1 Thread 2 “ I am Thread 1” “ I am Thread 2” Code in Thread n mutex_lock (PrinterMtx); printf (“I am Thread %d”, n); mutex_ unlock  (PrinterMtx); I am Thread 1 I am Thread 2
Mutex API pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t  *mutex_attr); int pthread_mutex_destroy (pthread_mutex_t *mutex); int pthread_mutex_lock (pthread_mutex_t *mutex); int pthread_mutex_unlock (pthread_mutex_t *mutex); int pthread_mutex_trylock (pthread_mutex_t *mutex);
Mutex Attributes int pthread_mutexattr_init (pthread_mutexattr_t *attr); int pthread_mutexattr_destroy (pthread_mutexattr_t *attr); #ifdef _POSIX_THREAD_PROCESS_SHARED int pthread_mutexattr_getpshared (pthread_mutexattr_t *attr, int *pshared); int pthread_mutexattr_setpshared (pthread_mutexattr_t *attr, int pshared); #endif int pthread_mutexattr_getkind_np (pthread_mutexattr_t *attr, int *kind); int pthread_mutexattr_setkind_np (pthread_mutexattr_t *attr, int kind);
Mutex “Kind” ,[object Object],[object Object],[object Object],[object Object],[object Object]
Priority Inversion Thread 1 Thread 2 Thread 3 Priority 1 3 2 Lock Lock Resource
Priority Inversion 2 Resource Thread 1 (priority 1) Thread 2 (priority 3) Thread 3 (priority 2) Thread 2 Lock Int Lock Int Block Unlock Thread 1
Priority Inversion Solutions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Priority Inversion Solutions II #if defined (_POSIX_THREAD_PRIO_PROTECT) || defined (_POSIX_THREAD_PRIO_INHERIT) int pthread_mutexattr_getprotocol (const pthread_mutexattr_t *attr, int *protocol); int pthread_mutexattr_setprotocol (pthread_mutexattr_t *attr, int protocol); #endif #ifdef _POSIX_THREAD_PRIO_PROTECT int pthread_mutexattr_getprioceiling (const pthread_mutexattr_t *attr, int *ceiling); int pthread_mutexattr_setprioceiling (pthread_mutexattr_t *attr, int ceiling); int pthread_mutex_getprioceiling (const pthread_mutex_t *mutex, int *ceiling); int pthread_mutex_setprioceiling (pthread_mutex_t * mutex, int ceiling); #endif
Conditional Variable ,[object Object],[object Object],[object Object]
Conditional Variable--Example Thread 1 Thread 2 Read Write Lock Lock Blocked
Conditional Variable API pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int pthread_cond_init (pthread_cond_t *cond, const pthread_condattr_t  *cond_attr); int pthread_cond_destroy (pthread_cond_t *cond); int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex,  const struct timespec *abstime); int pthread_cond_signal (pthread_cond_t *cond); int pthread_cond_broadcast (pthread_cond_t *cond);
Conditional Variable Attributes int pthread_condattr_init (pthread_condattr_t *attr); int pthread_condattr_destroy (pthread_condattr_t *attr); #ifdef _POSIX_THREAD_PROCESS_SHARED int pthread_condattr_getpshared (pthread_condattr_t *attr, int *pshared); int pthread_condattr_setpshared (pthread_condattr_t *attr, int pshared); #endif
// Declare a queue structure type queue_t void *write_queue_thread (void *arg) { queue_t *q = (queue_t *) arg; int status; while (1) { wait_for_data(); status = pthread_mutex_lock (&q->mutex); write_to_queue (q); status = pthread_cond_signal (&q->cond); status = pthread_mutex_unlock (&q->mutex); } } Continued on next slide
Continued from previous slide void *read_queue_thread (void *arg) { queue_t *q = (queue_t *) arg; int status; while (1) { status = pthread_mutex_lock (&q->mutex); if (queue_is_empty (q))   status = pthread_cond_wait (&q->cond); read_from_queue (q); status = pthread_mutex_unlock (&q->mutex); } }
Contention Scope ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],int pthread_attr_getscope (const pthread_attr_t *attr, int *contentionscope); int pthread_attr_setscope (const pthread_attr_t *attr, int contentionscope);
Threads in User Space Thr 1 Thr n Thread scheduler Process 1 Thr 1 Thr n Thread scheduler Process n Linux Kernel Read Blocks  all  threads in Process n Posix doesn’t allow this
“Many-to-one” Thread Mapping Pthread 1 Pthread 2 Pthread 3 Pthread 4 Kernel entity 1 Processor 1 Processor 2
Threads managed by the kernel Thr 1 Thr n Process 1 Thr 1 Thr n Process n Linux Kernel
“One-to-one” Thread Mapping Pthread 1 Pthread 2 Pthread 3 Pthread 4 Kernel entity 1 Processor 1 Processor 2 Kernel entity 2 Kernel entity 3 Kernel entity 4
Thread Cancellation int pthread_cancel (pthread_t thread); int pthread_setcancelstate (int state, int *oldstate); int pthread_setcanceltype (int type, int *oldtype); void pthread_testcancel (void); void pthread_cleanup_push (void (*routine)(void *), void *arg); void pthread_cleanup_pop (int execute);
Cancellation Type ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
include <pthread.h> include <stdio.h> int counter; void *thread_function (void *arg); { printf (“thread_function starting”); for (counter = 0; ; counter++) if ((counter % 1000) == 0) {   printf (“Calling testcancel”);   pthread_testcancel(); } } Int main (int argc, char *argv) { pthread_t thread_id; void *result; int status; status = pthread_create (&thread_id, NULL, thread_function, NULL); sleep (2); Continued on next slide
Continued from previous slide status = pthread_cancel (thread_id); status = pthread_join (thread_id, &result); if (result == PTHREAD_CANCELED) printf (“Thread canceled at iteration %d”, counter): else printf (“Thread not canceled”); }
“Cleanup Handlers” ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
typedef struct { . . pthread_mutext_t mutex; } control_t; void cleanup (void *arg) { control_ *st = (control_t *) arg; int status; pthread_mutex_unlock (&st->mutex) } Continued on next slide
Continued from previous slide void *thread_function (void *arg) { control_t *control = (control_t *) arg; while (1) { // do something local pthread_cleanup_push (cleanup, (void *) control); status = pthread_mutex_lock (&control->mutex); // Access common resource pthread_cleanup_pop (1); // do something else local } }
Native Posix Threading Library ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cancellation Mode

Más contenido relacionado

La actualidad más candente

Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Lecture 9 -_pthreads-linux_threads
Lecture 9 -_pthreads-linux_threadsLecture 9 -_pthreads-linux_threads
Lecture 9 -_pthreads-linux_threadsPrashant Pawar
 
Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++Shuo Chen
 
Where destructors meet threads
Where destructors meet threadsWhere destructors meet threads
Where destructors meet threadsShuo Chen
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Porting FreeRTOS on OpenRISC
Porting FreeRTOS   on   OpenRISCPorting FreeRTOS   on   OpenRISC
Porting FreeRTOS on OpenRISCYi-Chiao
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Semtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege EscalationSemtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege EscalationKernel TLV
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 

La actualidad más candente (20)

Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Lecture 9 -_pthreads-linux_threads
Lecture 9 -_pthreads-linux_threadsLecture 9 -_pthreads-linux_threads
Lecture 9 -_pthreads-linux_threads
 
Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Where destructors meet threads
Where destructors meet threadsWhere destructors meet threads
Where destructors meet threads
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Porting FreeRTOS on OpenRISC
Porting FreeRTOS   on   OpenRISCPorting FreeRTOS   on   OpenRISC
Porting FreeRTOS on OpenRISC
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Semtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege EscalationSemtex.c [CVE-2013-2094] - A Linux Privelege Escalation
Semtex.c [CVE-2013-2094] - A Linux Privelege Escalation
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
FreeRTOS
FreeRTOSFreeRTOS
FreeRTOS
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 

Destacado

PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 ThreadsRobert Sayegh
 
Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ahmar Hashmi
 
Distributed computing time
Distributed computing timeDistributed computing time
Distributed computing timeDeepak John
 
Flexible Symmetric Global Snapshot
Flexible Symmetric Global Snapshot Flexible Symmetric Global Snapshot
Flexible Symmetric Global Snapshot Ashutosh Jaiswal
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10huangachou
 
Distributed Snapshots
Distributed SnapshotsDistributed Snapshots
Distributed Snapshotsawesomesos
 
Creation of threads
Creation of threadsCreation of threads
Creation of threadsmyrajendra
 
Confronting the Future--Strategic Visions for the 21st Century Public Library
Confronting the Future--Strategic Visions for the 21st Century Public LibraryConfronting the Future--Strategic Visions for the 21st Century Public Library
Confronting the Future--Strategic Visions for the 21st Century Public LibraryMarc Gartler
 
Global state recording in Distributed Systems
Global state recording in Distributed SystemsGlobal state recording in Distributed Systems
Global state recording in Distributed SystemsArsnet
 
network filesystem briefs
network filesystem briefsnetwork filesystem briefs
network filesystem briefsbergwolf
 
Concurrent programming in iOS
Concurrent programming in iOSConcurrent programming in iOS
Concurrent programming in iOSDongxu Yao
 
Day 2 global_state_and_snapshot_algorithms
Day 2 global_state_and_snapshot_algorithmsDay 2 global_state_and_snapshot_algorithms
Day 2 global_state_and_snapshot_algorithmsVI Ni
 
6 Dean Google
6 Dean Google6 Dean Google
6 Dean GoogleFrank Cai
 
LDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolLDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolS. Hasnain Raza
 
Staff study talk/ on search engine & internet in 2008
Staff study talk/ on search engine & internet in 2008Staff study talk/ on search engine & internet in 2008
Staff study talk/ on search engine & internet in 2008Sujit Chandak
 

Destacado (20)

Pthread
PthreadPthread
Pthread
 
PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 Threads
 
Ch5: Threads (Operating System)
Ch5: Threads (Operating System)Ch5: Threads (Operating System)
Ch5: Threads (Operating System)
 
Distributed computing time
Distributed computing timeDistributed computing time
Distributed computing time
 
Flexible Symmetric Global Snapshot
Flexible Symmetric Global Snapshot Flexible Symmetric Global Snapshot
Flexible Symmetric Global Snapshot
 
LDAP
LDAPLDAP
LDAP
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
 
Distributed Snapshots
Distributed SnapshotsDistributed Snapshots
Distributed Snapshots
 
Creation of threads
Creation of threadsCreation of threads
Creation of threads
 
Confronting the Future--Strategic Visions for the 21st Century Public Library
Confronting the Future--Strategic Visions for the 21st Century Public LibraryConfronting the Future--Strategic Visions for the 21st Century Public Library
Confronting the Future--Strategic Visions for the 21st Century Public Library
 
Phase1 review ws-intro-2_km&julian
Phase1 review ws-intro-2_km&julianPhase1 review ws-intro-2_km&julian
Phase1 review ws-intro-2_km&julian
 
Global state recording in Distributed Systems
Global state recording in Distributed SystemsGlobal state recording in Distributed Systems
Global state recording in Distributed Systems
 
network filesystem briefs
network filesystem briefsnetwork filesystem briefs
network filesystem briefs
 
Concurrent programming in iOS
Concurrent programming in iOSConcurrent programming in iOS
Concurrent programming in iOS
 
Day 2 global_state_and_snapshot_algorithms
Day 2 global_state_and_snapshot_algorithmsDay 2 global_state_and_snapshot_algorithms
Day 2 global_state_and_snapshot_algorithms
 
6 Dean Google
6 Dean Google6 Dean Google
6 Dean Google
 
AD & LDAP
AD & LDAPAD & LDAP
AD & LDAP
 
LDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access ProtocolLDAP - Lightweight Directory Access Protocol
LDAP - Lightweight Directory Access Protocol
 
Coda file system tahir
Coda file system   tahirCoda file system   tahir
Coda file system tahir
 
Staff study talk/ on search engine & internet in 2008
Staff study talk/ on search engine & internet in 2008Staff study talk/ on search engine & internet in 2008
Staff study talk/ on search engine & internet in 2008
 

Similar a Posix Threads

Unit 4
Unit 4Unit 4
Unit 4siddr
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxSoumen Santra
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptxsibokac
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 ProcessShu-Yu Fu
 
GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPMiller Lee
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3Peter Tröger
 
Parallel program design
Parallel program designParallel program design
Parallel program designZongYing Lyu
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6fisher.w.y
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Python-GTK
Python-GTKPython-GTK
Python-GTKYuren Ju
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)Sri Prasanna
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework HelpC++ Homework Help
 

Similar a Posix Threads (20)

Unit 4
Unit 4Unit 4
Unit 4
 
Sysprog 14
Sysprog 14Sysprog 14
Sysprog 14
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel Development
 
OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3
 
Parallel program design
Parallel program designParallel program design
Parallel program design
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Crash course in verilog
Crash course in verilogCrash course in verilog
Crash course in verilog
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 

Posix Threads

  • 1. Introduction to POSIX Threads Asynchronous Programming in a Unix/Linux Environment Doug Abbott Silver City, NM 575-388-4879 email: [email_address] web: www. Intellimetrix.us Class #308
  • 2.
  • 3. The Interrupt Mainline Instruction Execution “ Event” Interrupt Service Routine
  • 4. Interrupts Cause Problems Thread 1 Thread 2 Data Structure while (1) { wait for (event1); write (data_structure); } while (1) { wait for (event2); read (data_structure); } Priority 1 Priority 2
  • 5. The Real-time Programming Problem Thread 2 while (1) { Reading data structure; INTERRUPT (event 1)! Still reading data structure; (but data has changed!) } Thread 1 executes!
  • 6.
  • 7. “ Processes” vs “Threads” DATA CODE DATA CODE DATA CODE UNIX Process Model DATA THREAD 1 THREAD 2 THREAD 3 Multi-threaded Process
  • 8.
  • 9. Thread API int pthread_create (pthread_t *thread, pthread_attr_t *attr, void *(* start_ routine) (void *), void *arg); void pthread_exit (void *retval); int pthread_join (pthread_t thread, void **thread_return); pthread_t pthread_self (void); int sched_yield (void);
  • 10. /* Thread Example */ #include <pthread.h> #include &quot;errors.h&quot; /* * Thread start routine. */ void *thread_routine (void *arg) { printf (&quot;%s&quot;), arg); return arg; } main (int argc, char *argv[]) { pthread_t thread_id; void *thread_result; int status; status = pthread_create (&thread_id, NULL, thread_routine, (void *)argv[0]); printf (&quot;New thread created&quot;); status = pthread_join (thread_id, thread_result); printf (&quot;Thread returned %p&quot;, thread_result); return 0; }
  • 11. Thread State Diagram Ready Blocked Running Terminated created scheduled preempted wait for resource wait satisfied done or cancelled
  • 12.
  • 13.
  • 14.
  • 15. /* Thread Attributes */ #include <limits.h> #include <pthread.h> void *thread_routine (void *arg) {/ * Thread start routine. Reports it ran, and then exits. */ printf (&quot;The thread is here&quot;); return NULL; } int main (int argc, char *argv[]) { pthread_t thread_id; pthread_attr_t thread_attr; size_t stack_size; int status; status = pthread_attr_init (&thread_attr); status = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); #ifdef _POSIX_THREAD_ATTR_STACKSIZE / * Set stack size to twice the minimum */ status = pthread_attr_getstacksize (&thread_attr, &stack_size); printf (&quot;Default stack size is %u; minimum is %u&quot;, stack_size, PTHREAD_STACK_MIN); status = pthread_attr_setstacksize (&thread_attr, PTHREAD_STACK_MIN*2); #endif status = pthread_create (&thread_id, &thread_attr, thread_routine, NULL); printf (&quot;Main exiting&quot;); return 0; }
  • 16. Thread Scheduling int pthread_attr_setschedparam (pthread_attr_t *attr, const struct sched_param *param); int pthread_attr_getschedparam (const pthread_attr_t *attr, struct sched_param *param); int pthread_attr_setschedpolicy (pthread_attr_t *attr, int policy); int pthread_attr_getschedpolicy (const pthread_attr_t *attr, int *policy); int pthread_attr_setinheritsched (pthread_attr_t *attr, int inherit); int pthread_attr_getinheritsched (const pthread_attr_t *attr, int *inherit); int pthread_setschedparam (pthread_t pthread, int *policy, const struct sched_param *param); int pthread_getschedparam (pthread_t pthread, int *policy, struct sched_param *param); int sched_get_priority_max (int policy); int sched_get_priority_min (int policy); Optional Thread Attributes
  • 17.
  • 18. Scheduling: Non-Preemptive vs Preemptive ISR Task Hi Task Lo Blocks Interrupt Ready ISR Task Hi Task Lo NON-PREEMPTIVE PREEMPTIVE Ready
  • 19.
  • 20. return addr Reentrancy--What is it void fun1 (int a, int b) { int i, j; i = a; j = b; . . } b a i j stack pointer Stack “frame” for fun1 Stack
  • 21. return addr A Non-reentrant Function int j; void fun2 (int a, int b) { int i; i = a; j = b; if (j == 0) { } } b a i Stack sp j Heap
  • 22. Sharing Resources Thread 1 Thread 2 “ I am Thread 1” “ I am Thread 2” “ II a amm ThThrreeadad 12” Code in Thread n printf (“I am Thread %d”, n);
  • 23. Sharing Resources with a Mutex Thread 1 Thread 2 “ I am Thread 1” “ I am Thread 2” Code in Thread n mutex_lock (PrinterMtx); printf (“I am Thread %d”, n); mutex_ unlock (PrinterMtx); I am Thread 1 I am Thread 2
  • 24. Mutex API pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutex_attr); int pthread_mutex_destroy (pthread_mutex_t *mutex); int pthread_mutex_lock (pthread_mutex_t *mutex); int pthread_mutex_unlock (pthread_mutex_t *mutex); int pthread_mutex_trylock (pthread_mutex_t *mutex);
  • 25. Mutex Attributes int pthread_mutexattr_init (pthread_mutexattr_t *attr); int pthread_mutexattr_destroy (pthread_mutexattr_t *attr); #ifdef _POSIX_THREAD_PROCESS_SHARED int pthread_mutexattr_getpshared (pthread_mutexattr_t *attr, int *pshared); int pthread_mutexattr_setpshared (pthread_mutexattr_t *attr, int pshared); #endif int pthread_mutexattr_getkind_np (pthread_mutexattr_t *attr, int *kind); int pthread_mutexattr_setkind_np (pthread_mutexattr_t *attr, int kind);
  • 26.
  • 27. Priority Inversion Thread 1 Thread 2 Thread 3 Priority 1 3 2 Lock Lock Resource
  • 28. Priority Inversion 2 Resource Thread 1 (priority 1) Thread 2 (priority 3) Thread 3 (priority 2) Thread 2 Lock Int Lock Int Block Unlock Thread 1
  • 29.
  • 30. Priority Inversion Solutions II #if defined (_POSIX_THREAD_PRIO_PROTECT) || defined (_POSIX_THREAD_PRIO_INHERIT) int pthread_mutexattr_getprotocol (const pthread_mutexattr_t *attr, int *protocol); int pthread_mutexattr_setprotocol (pthread_mutexattr_t *attr, int protocol); #endif #ifdef _POSIX_THREAD_PRIO_PROTECT int pthread_mutexattr_getprioceiling (const pthread_mutexattr_t *attr, int *ceiling); int pthread_mutexattr_setprioceiling (pthread_mutexattr_t *attr, int ceiling); int pthread_mutex_getprioceiling (const pthread_mutex_t *mutex, int *ceiling); int pthread_mutex_setprioceiling (pthread_mutex_t * mutex, int ceiling); #endif
  • 31.
  • 32. Conditional Variable--Example Thread 1 Thread 2 Read Write Lock Lock Blocked
  • 33. Conditional Variable API pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int pthread_cond_init (pthread_cond_t *cond, const pthread_condattr_t *cond_attr); int pthread_cond_destroy (pthread_cond_t *cond); int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); int pthread_cond_signal (pthread_cond_t *cond); int pthread_cond_broadcast (pthread_cond_t *cond);
  • 34. Conditional Variable Attributes int pthread_condattr_init (pthread_condattr_t *attr); int pthread_condattr_destroy (pthread_condattr_t *attr); #ifdef _POSIX_THREAD_PROCESS_SHARED int pthread_condattr_getpshared (pthread_condattr_t *attr, int *pshared); int pthread_condattr_setpshared (pthread_condattr_t *attr, int pshared); #endif
  • 35. // Declare a queue structure type queue_t void *write_queue_thread (void *arg) { queue_t *q = (queue_t *) arg; int status; while (1) { wait_for_data(); status = pthread_mutex_lock (&q->mutex); write_to_queue (q); status = pthread_cond_signal (&q->cond); status = pthread_mutex_unlock (&q->mutex); } } Continued on next slide
  • 36. Continued from previous slide void *read_queue_thread (void *arg) { queue_t *q = (queue_t *) arg; int status; while (1) { status = pthread_mutex_lock (&q->mutex); if (queue_is_empty (q)) status = pthread_cond_wait (&q->cond); read_from_queue (q); status = pthread_mutex_unlock (&q->mutex); } }
  • 37.
  • 38. Threads in User Space Thr 1 Thr n Thread scheduler Process 1 Thr 1 Thr n Thread scheduler Process n Linux Kernel Read Blocks all threads in Process n Posix doesn’t allow this
  • 39. “Many-to-one” Thread Mapping Pthread 1 Pthread 2 Pthread 3 Pthread 4 Kernel entity 1 Processor 1 Processor 2
  • 40. Threads managed by the kernel Thr 1 Thr n Process 1 Thr 1 Thr n Process n Linux Kernel
  • 41. “One-to-one” Thread Mapping Pthread 1 Pthread 2 Pthread 3 Pthread 4 Kernel entity 1 Processor 1 Processor 2 Kernel entity 2 Kernel entity 3 Kernel entity 4
  • 42. Thread Cancellation int pthread_cancel (pthread_t thread); int pthread_setcancelstate (int state, int *oldstate); int pthread_setcanceltype (int type, int *oldtype); void pthread_testcancel (void); void pthread_cleanup_push (void (*routine)(void *), void *arg); void pthread_cleanup_pop (int execute);
  • 43.
  • 44. include <pthread.h> include <stdio.h> int counter; void *thread_function (void *arg); { printf (“thread_function starting”); for (counter = 0; ; counter++) if ((counter % 1000) == 0) { printf (“Calling testcancel”); pthread_testcancel(); } } Int main (int argc, char *argv) { pthread_t thread_id; void *result; int status; status = pthread_create (&thread_id, NULL, thread_function, NULL); sleep (2); Continued on next slide
  • 45. Continued from previous slide status = pthread_cancel (thread_id); status = pthread_join (thread_id, &result); if (result == PTHREAD_CANCELED) printf (“Thread canceled at iteration %d”, counter): else printf (“Thread not canceled”); }
  • 46.
  • 47. typedef struct { . . pthread_mutext_t mutex; } control_t; void cleanup (void *arg) { control_ *st = (control_t *) arg; int status; pthread_mutex_unlock (&st->mutex) } Continued on next slide
  • 48. Continued from previous slide void *thread_function (void *arg) { control_t *control = (control_t *) arg; while (1) { // do something local pthread_cleanup_push (cleanup, (void *) control); status = pthread_mutex_lock (&control->mutex); // Access common resource pthread_cleanup_pop (1); // do something else local } }
  • 49.