Netprog: Threads Programming

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

Threads. Readings r Silberschatz et al : Chapter 4.
Threads Programming Thread creation Synchronization.
Multi-core Programming Programming with Posix Threads.
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Lecture 12 Overview. UDP Connected mode A UDP socket can be used in a call to connect() This simply tells the O.S. the address of the peer No handshake.
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.
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.
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© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
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.
CSE Computer Networks Prof. Aaron Striegel Department of Computer Science & Engineering University of Notre Dame Lecture 7 – February 2, 2010.
The University of Adelaide, School of Computer Science
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
Today’s topic Pthread Some materials and figures are obtained from the POSIX threads Programming tutorial at
Concurrency. Readings r Tanenbaum and van Steen: r Coulouris: Chapter 6 r cs402 web page links r UNIX Network Programming by W. Richard Stevens.
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Programming with POSIX* Threads Intel Software College.
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
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.
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
Pthreads.
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.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
回到第一頁 What are threads n Threads are often called "lightweight processes” n In the UNIX environment a thread: u Exists within a process and uses the process.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
Realizing Concurrency using the thread model
CS 537 – Introduction to Operating Systems
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Realizing Concurrency using the thread model
Threads in C Caryl Rahn.
Shared-Memory Programming with Threads
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Thread Programming.
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Thread Programming.
Realizing Concurrency using the thread model
Unix System Calls and Posix Threads
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Chien-Chung Shen CIS/UD
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
POSIX Threads(pthreads)
Presentation transcript:

Netprog: Threads Programming Refs: Chapter 23 Netprog: Threads Programming

Netprog: Threads Programming Threads vs. Processes Creation of a new process using fork is expensive (time & memory). A thread (sometimes called a lightweight process) does not require lots of memory or startup time. Netprog: Threads Programming

Netprog: Threads Programming fork() Process A Global Variables Code Stack fork() Process B Global Variables Code Stack Netprog: Threads Programming

Netprog: Threads Programming pthread_create() Process A Thread 1 Global Variables Code Stack pthread_create() Process A Thread 2 Stack Netprog: Threads Programming

Netprog: Threads Programming Multiple Threads Each process can include many threads. All threads of a process share: memory (program code and global data) open file/socket descriptors signal handlers and signal dispositions working environment (current directory, user ID, etc.) Netprog: Threads Programming

Thread-Specific Resources Each thread has it’s own: Thread ID (integer) Stack, Registers, Program Counter errno (if not - errno would be useless!) Threads within the same process can communicate using shared memory. Must be done carefully! Netprog: Threads Programming

Netprog: Threads Programming Posix Threads We will focus on Posix Threads - most widely supported threads programming API. Solaris - you need to link with “-lpthread” On many systems this also forces the compiler to link in re-entrant libraries (instead of plain vanilla C libraries). Netprog: Threads Programming

Netprog: Threads Programming Thread Creation pthread_create( pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void *), void *arg); func is the function to be called. When func() returns the thread is terminated. Netprog: Threads Programming

Netprog: Threads Programming pthread_create() The return value is 0 for OK. positive error number on error. Does not set errno !!! Thread ID is returned in tid Netprog: Threads Programming

Netprog: Threads Programming pthread_t *tid The book says you can specify NULL for tid (thread ID), I've found this doesn't always work! Thread attributes can be set using attr, including detached state and scheduling policy. You can specify NULL and get the system defaults. Netprog: Threads Programming

Netprog: Threads Programming Thread IDs Each thread has a unique ID, a thread can find out it's ID by calling pthread_self(). Thread IDs are of type pthread_t which is usually an unsigned int. When debugging, it's often useful to do something like this: printf("Thread %u:\n",pthread_self()); Netprog: Threads Programming

Netprog: Threads Programming Thread Arguments When func() is called the value arg specified in the call to pthread_create() is passed as a parameter. func can have only 1 parameter, and it can't be larger than the size of a void *. Netprog: Threads Programming

Thread Arguments (cont.) Complex parameters can be passed by creating a structure and passing the address of the structure. The structure can't be a local variable (of the function calling pthread_create)!! - threads have different stacks! Netprog: Threads Programming

Netprog: Threads Programming Thread args example struct { int x,y } 2ints; void *blah( void *arg) { struct 2ints *foo = (struct 2ints *) arg; printf("%u sum of %d and %d is %d\n", pthread_self(), foo->x, foo->y, foo->x+foo->y); return(NULL); } Netprog: Threads Programming

Netprog: Threads Programming Thread Lifespan Once a thread is created, it starts executing the function func() specified in the call to pthread_create(). If func() returns, the thread is terminated. A thread can also be terminated by calling pthread_exit(). If main() returns or any thread calls exit()all threads are terminated. Netprog: Threads Programming

Netprog: Threads Programming Detached State Each thread can be either joinable or detached. Detached: on termination all thread resources are released by the OS. A detached thread cannot be joined. No way to get at the return value of the thread. ( a pointer to something: void * ). Netprog: Threads Programming

Netprog: Threads Programming Joinable Thread Joinable: on thread termination the thread ID and exit status are saved by the OS. One thread can "join" another by calling pthread_join - which waits (blocks) until a specified thread exits. int pthread_join( pthread_t tid, void **status); Netprog: Threads Programming

Shared Global Variables int counter=0; void *pancake(void *arg) { counter++; printf("Thread %u is number %d\n", pthread_self(),counter); } main() { int i; pthread_t tid; for (i=0;i<10;i++) pthread_create(&tid,NULL,pancake,NULL); Netprog: Threads Programming

Netprog: Threads Programming DANGER! DANGER! DANGER! Sharing global variables is dangerous - two threads may attempt to modify the same variable at the same time. Just because you don't see a problem when running your code doesn't mean it can't and won't happen!!!! Netprog: Threads Programming

Netprog: Threads Programming Avoiding Problems pthreads includes support for Mutual Exclusion primitives that can be used to protect against this problem. The general idea is to lock something before accessing global variables and to unlock as soon as you are done. Shared socket descriptors should be treated as global variables!!! Netprog: Threads Programming

Netprog: Threads Programming pthread_mutex A global variable of type pthread_mutex_t is required: pthread_mutex_t counter_mtx= PTHREAD_MUTEX_INITIALIZER; Initialization to PTHREAD_MUTEX_INITIALIZER is required for a static variable! Netprog: Threads Programming

Netprog: Threads Programming Locking and Unlocking To lock use: pthread_mutex_lock(pthread_mutex_t &); To unlock use: pthread_mutex_unlock(pthread_mutex_t &); Both functions are blocking! Netprog: Threads Programming

Example Problem (Pop Tart Quiz) A server creates a thread for each client. No more than n threads (and therefore n clients) can be active at once. How can we have the main thread know when a child thread has terminated and it can now service a new client? Netprog: Threads Programming

pthread_join() doesn’t help pthread_join (which is sort of like wait()) requires that we specify a thread id. We can wait for a specific thread, but we can't wait for "the next thread to exit". Netprog: Threads Programming

Use a western omelet global variable? When each thread starts up: acquires a lock on the variable (using a mutex) increments the variable releases the lock. When each thread shuts down: decrements the variable Netprog: Threads Programming

What about the fruit main loop? active_threads=0; // start up n threads on first n clients // make sure they are all running while (1) { // have to lock/relase active_threads if (active_threads < n) // start up thread for next client busy_ waiting(is_bad); } Netprog: Threads Programming

Netprog: Threads Programming Condition Variables pthreads support condition variables, which allow one thread to wait (sleep) for an event generated by any other thread. This allows us to avoid the busy waiting problem. pthread_cond_t foo = PTHREAD_COND_INITIALIZER; Netprog: Threads Programming

Condition Variables (cont.) A condition variable is always used with mutex. pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr); pthread_cond_signal(pthread_cond_t *cptr); don’t let the word signal confuse you - this has nothing to do with Unix signals Netprog: Threads Programming

Netprog: Threads Programming Revised menu strategy Each thread decrements active_threads when terminating and calls pthread_cond_signal to wake up the main loop. The main thread increments active_threads when each thread is started and waits for changes by calling pthread_cond_wait. Netprog: Threads Programming

Netprog: Threads Programming Revised menu strategy All changes to active_threads must be inside the lock and release of a mutex. If two threads are ready to exit at (nearly) the same time – the second must wait until the main loop recognizes the first. We don’t lose any of the condition signals. Netprog: Threads Programming

Netprog: Threads Programming Global Variables // global variable the number of active // threads (clients) int active_threads=0; // mutex used to lock active_threads pthread_mutex_t at_mutex = PTHREAD_MUTEX_INITIALIZER; // condition var. used to signal changes pthread_cond_t at_cond = PTHREAD_COND_INITIALIZER; Netprog: Threads Programming

Netprog: Threads Programming Child Thread Code void *cld_func(void *arg) { . . . // handle the client pthread_mutex_lock(&at_mutex); active_threads--; pthread_cond_signal(&at_cond); pthread_mutex_unlock(&at_mutex); return(); } Netprog: Threads Programming

Netprog: Threads Programming Main thread IMPORTANT! Must happen while the mutex lock is held. // no need to lock yet active_threads=0; while (1) { pthread_mutex_lock(&at_mutex); while (active_threads < n ) { active_threads++; pthread_start(…) } pthread_cond_wait( &at_cond, &at_mutex); pthread_mutex_unlock(&at_mutex); Netprog: Threads Programming

Other pastries pthread functions Sometimes a function needs to have thread specific data (for example, a function that uses a static local). Functions that support thread specific data: pthread_key_create() pthread_once() pthread_getspecific() pthread_setspecific() The book has a nice example creating a safe and efficient readline() Netprog: Threads Programming

Thread Safe library functions You have to be careful with libraries. If a function uses any static variables (or global memory) it’s not safe to use with threads! The book has a list of the Posix thread-safe functions… Netprog: Threads Programming

Breakfast Thread Summary Threads are awesome, but dangerous. You have to pay attention to details or it's easy to end up with code that is incorrect (doesn't always work, or hangs in deadlock). Posix threads provides support for mutual exclusion, condition variables and thread-specific data. IHOP serves breakfast 24 hours a day! Netprog: Threads Programming