Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.

Slides:



Advertisements
Similar presentations
Threads Relation to processes Threads exist as subsets of processes Threads share memory and state information within a process Switching between threads.
Advertisements

CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Threads Programming Thread creation Synchronization.
Programming with Posix Threads CS5204 Operating Systems.
Multi-core Programming Programming with Posix Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Chap. 23 Threads (1) Threads v.s. Fork (2) Basic Thread Functions #include int pthread_create ( pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void.
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
POSIX Threads Nezer J. Zaidenberg. References  Advanced programming for the UNIX environment (2nd edition. This material does not exist in first edition)
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
02/01/2007CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook.
B.Ramamurthy1 POSIX Thread Programming 2/14/97 B.Ramamurthy.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
02/02/2004CSCI 315 Operating Systems Design1 Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook Operating.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Threads A thread (or lightweight process) is a basic unit of CPU.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
POSIX Threads Nezer J. Zaidenberg. References  Advanced programming for the UNIX environment (2nd edition chapter This material does not exist.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
What is a thread? process: an address space with 1 or more threads executing within that address space, and the required system resources for those threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Programming with POSIX* Threads Intel Software College.
Condition Variables u A condition variable is used to wait until a particular condition is true  like in a monitor u Always use condition variables together.
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,
Threads and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Thread API Xiaohua Lu Office : CS 3310 Tel. : Office hours: 11-12,3-5 T,TR.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
POSIX Threads HUJI Spring 2011.
Pthreads.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 14 Threads 2 Read Ch.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
pThread synchronization
CMSC 421 Spring 2004 Section 0202 Part II: Process Management Chapter 5 Threads.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Synchronization and Semaphores
CS 537 – Introduction to Operating Systems
PThreads.
Shared-Memory Programming with Threads
Threads Threads.
Netprog: Threads Programming
Thread Programming.
Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Operating Systems Lecture 13.
Thread Programming.
BOOM! count is [ ], should be
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Synchronization Primitives – Semaphore and Mutex
Outline Chapter 3: Processes Chapter 4: Threads So far - Next -
POSIX Threads(pthreads)
Presentation transcript:

Introduction to Pthreads

Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model popular – nowadays practically all major thread libraries on Unix systems are Pthreads-compatible

Preliminaries Include pthread.h in the main file Compile program with –lpthread –gcc –o test test.c –lpthread –may not report compilation errors otherwise but calls will fail Good idea to check return values on common functions

Thread creation Types: pthread_t – type of a thread Some calls: int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void * (*start_routine)(void *), void *arg); int pthread_join(pthread_t thread, void **status); int pthread_detach(); void pthread_exit(); –No explicit parent/child model, except main thread holds process info –Call pthread_exit in main, don’t just fall through; –Most likely you wouldn’t need pthread_join status = exit value returned by joinable thread –Detached threads are those which cannot be joined (can also set this at creation)

Attributes Type: pthread_attr_t (see pthread_create ) Attributes define the state of the new thread Attributes: system scope, joinable, stack size, inheritance… you can use default behaviors with NULL in pthread_create() int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t *attr); pthread_attr_{set/get}{attribute} Example: pthread_attr_t attr; pthread_attr_init(&attr); // Needed!!! pthread_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_create(NULL, &attr, foo, NULL);

Contention Scope Contention scope is the POSIX term for describing bound and unbound threads A bound thread is said to have system contention scope –i.e., it contends with all threads in the system An unbound thread has process contention scope –i.e., it contends with threads in the same process You can experiment in your project with this, but for most practical reasons use bound threads (system scope) –Solaris LWP switching cheap, Linux is one-to-one anyways…

Pthread Mutexes Type: pthread_mutex_t int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *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); Attributes: for shared mutexes/condition vars among processes, for priority inheritance, etc. –use defaults Important: Mutex scope must be visible to all threads!

Condition variables Type pthread_cond_t int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); int pthread_cond_destroy(pthread_cond_t *cond); int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_singal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t *cond);

Some rules… Shared data should always be accessed through a single mutex (write a comment) Think of a boolean condition (expressed in terms of program variables) for each condition variable. Every time the value of the boolean condition may have changed, call Broadcast for the condition variable –Only call Signal when you are absolutely certain that any and only one waiting thread can enter the critical section –if noone is waiting, signal is lost Signaling/Broadcasting thread need not have the mutex –may be more efficient to release it first… Globally order locks, acquire in order in all threads

Examples follow…

#include /* Example program creating thread to compute square of value */ int value; /* thread stores result here */ void *my_thread(void *param); /* the thread */ main (int argc, char *argv[]) { pthread_t tid;/* thread identifier */ int retcode; /* check input parameters */ if (argc != 2) { fprintf (stderr, "usage: a.out \n"); exit(0); } /* create the thread */ retcode = pthread_create(&tid,NULL,my_thr ead,argv[1]); if (retcode != 0) { fprintf (stderr, "Unable to create thread\n"); exit (1); } /* wait for created thread to exit */ pthread_join(tid,NULL); printf ("I am the parent: Square = %d\n", value); } //main /* The thread will begin control in this function */ void *my_thread(void *param) { int i = atoi (param); printf ("I am the child, passed value %d\n", i); value = i * i; /* next line is not really necessary */ pthread_exit(0); }

#include /* Producer/consumer program illustrating conditional variables */ /* Size of shared buffer */ #define BUF_SIZE 3 int buffer[BUF_SIZE];/*shared buffer */ int add=0;/* place to add next element */ int rem=0;/* place to remove next element */ int num=0;/* number elements in buffer */ pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;/* mutex lock for buffer */ pthread_cond_t c_cons=PTHREAD_COND_INITIALIZER; /* consumer waits on this cond var */ pthread_cond_t c_prod=PTHREAD_COND_INITIALIZER; /* producer waits on this cond var */ void *producer(void *param); void *consumer(void *param);

main (int argc, char *argv[]) { pthread_t tid1, tid2;/* thread identifiers */ int i; /* create the threads; may be any number, in general */ if (pthread_create(&tid1,NULL,producer,NULL) != 0) { fprintf (stderr, "Unable to create producer thread\n"); exit (1); } if (pthread_create(&tid2,NULL,consumer,NULL) != 0) { fprintf (stderr, "Unable to create consumer thread\n"); exit (1); } /* wait for created thread to exit */ pthread_join(tid1,NULL); pthread_join(tid2,NULL); printf ("Parent quiting\n"); }

/* Produce value(s) */ void *producer(void *param) { int i; for (i=1; i<=20; i++) { /* Insert into buffer */ pthread_mutex_lock (&m); if (num > BUF_SIZE) exit(1);/* overflow */ while (num == BUF_SIZE)/* block if buffer is full */ pthread_cond_wait (&c_prod, &m); /* if executing here, buffer not full so add element */ buffer[add] = i; add = (add+1) % BUF_SIZE; num++; pthread_mutex_unlock (&m); pthread_cond_signal (&c_cons); printf ("producer: inserted %d\n", i); fflush (stdout); } printf ("producer quiting\n"); fflush (stdout); }

/* Consume value(s); Note the consumer never terminates */ void *consumer(void *param) { int i; while (1) { pthread_mutex_lock (&m); if (num < 0) exit(1); /* underflow */ while (num == 0) /* block if buffer empty */ pthread_cond_wait (&c_cons, &m); /* if executing here, buffer not empty so remove element */ i = buffer[rem]; rem = (rem+1) % BUF_SIZE; num--; pthread_mutex_unlock (&m); pthread_cond_signal (&c_prod); printf ("Consume value %d\n", i); fflush(stdout); }