Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.

Slides:



Advertisements
Similar presentations
Threads Programming Thread creation Synchronization.
Advertisements

Threads. What do we have so far The basic unit of CPU utilization is a process. To run a program (a sequence of code), create a process. Processes are.
TELE 402 Lecture 11: Advanced UDP… 1 by Dr Z. Huang Overview Last Lecture –Nonblocking I/O and ioctl operations –Source: Chapter 16 & 17 of Stevens’ book.
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
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.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
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.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
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.
Introduction to Threads CS240 Programming in C. Introduction to Threads A thread is a path execution By default, a C/C++ program has one thread called.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Processes & Threads Emery Berger and Mark Corner University.
Programming with TCP – III 1. Zombie Processes 2. Cleaning Zombie Processes 3. Concurrent Servers Using Threads  pthread Library Functions 4. TCP Socket.
1 Confidential Enterprise Solutions Group Process and Threads.
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.
1 Concurrent Programming. 2 Outline Concurrent programming –Processes –Threads Suggested reading: –12.1, 12.3.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
CS333 Intro to Operating Systems Jonathan Walpole.
Week 16 (April 25 th ) Outline Thread Synchronization Lab 7: part 2 & 3 TA evaluation form Reminders Lab 7: due this Thursday Final review session Final.
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.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Pthreads.
P4: Multithreaded Programming Zhenxiao Luo CS537 Spring 2010.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
Processes, Threads, and Process States. Programs and Processes  Program: an executable file (before/after compilation)  Process: an instance of a program.
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.
CSC 360, Instructor: Kui Wu Thread & PThread. CSC 360, Instructor: Kui Wu Agenda 1.What is thread? 2.User vs kernel threads 3.Thread models 4.Thread issues.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Threads A thread is an alternative model of program execution
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
Concurrency I: Threads Nov 9, 2000 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
Concurrency Threads Synchronization Thread-safety of Library Functions Anubhav Gupta Dec. 2, 2002 Outline.
Programming with Threads. Threads  Sometimes called a lightweight process  smaller execution unit than a process  Consists of:  program counter 
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
1 Introduction to Threads Race Conditions. 2 Process Address Space Revisited Code Data OS Stack (a)Process with Single Thread (b) Process with Two Threads.
pThread synchronization
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Instructor: Haryadi Gunawi
Threads Synchronization Thread-safety of Library Functions
Threads in C Caryl Rahn.
Threads Threads.
Netprog: Threads Programming
CS399 New Beginnings Jonathan Walpole.
Thread Programming.
Linux Processes & Threads
Concurrent Programming November 13, 2008
Thread synchronization
Concurrent Servers Topics Limitations of iterative servers
Thread Programming.
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Concurrent Programming CSCI 380: Operating Systems
Concurrent Programming November 13, 2008
Threads CSE 2431: Introduction to Operating Systems
Presentation transcript:

Threads Chapter 26

Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is expensive 10 to 100 times slower Copy of everything in parent. Inter process communication For returning information from child to parent

Threads… Shared components Global memory Instructions Most data Open descriptors (files, sockets etc) Signal handlers Not shared Registers, Program counter, stack pointer Thread ID Stack Errno Priority

Advantages of Threads Light-weight Lower Context Switching Overhead Fewer OS resources Shared State Don’t need IPC-like mechanism to communicate between threads of same process

Disadvantages of Threads Shared State! Global variables are shared between threads. Accidental changes can be fatal. Many library functions are not thread-safe Library Functions that return pointers to static internal memory. E.g. gethostbyname() Lack of robustness Crash in one thread will crash the entire process.

Creation Thread equivalent of fork() int pthread_create( pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg ); Returns 0 if OK, and non-zero (> 0) if error.

Termination Thread Termination Return from initial function. void pthread_exit(void * status) Process Termination exit() called by any thread main() returns

Waiting for child thread int pthread_join( pthread_t tid, void **status) Equivalent of waitpid() for processes

Detaching a thread The detached thread can act as daemon thread The parent thread doesn’t need to wait int pthread_detach(pthread_t tid) Detaching self : pthread_detach(pthread_self())

Echo client-server Read Thread Write Thread Read Thread Write Thread Read Write Read Client1 Client2 Server S1S2 listenfd

Thread-based Echo Server

main() { int listenfd, connfd; int len; pthread_t tid; /* Start the usual way */ listenfd = Socket( … ); Bind(listenfd, … ); Listen(listenfd, … ) for ( ; ; ) { len = addrlen; connfd = Accept(listenfd, … ); /* Create a thread in service_func routine */ Pthread_create(&tid, NULL, service_func, ???? ); } How to pass connfd? (void *) arg

main() { int listenfd, connfd; int len; pthread_t tid; /* Start the usual way */ listenfd = Socket( … ); Bind(listenfd, … ); Listen(listenfd, … ) for ( ; ; ) { len = addrlen; cptr = Malloc(sizeof(int)); *cptr = Accept(listenfd, … ); /* Create a thread in service_func routine */ Pthread_create(&tid, NULL, service_func, (void *) cptr); }

void * service_func(void *arg) { int local_connfd; /* release parent from waiting */ Pthread_detach(pthread_self()); /* extract connfd from argument */ local_connfd = *((int *) arg); free(arg); /* receive and echo client ’ s message See Figure 5.3, page 124, Steven ’ s book*/ str_echo(local_connfd); /* Terminate the connection */ Close(local_connfd); return(NULL); }

Thread-based Echo Client Why is single threaded client not good enough? Multi-threaded Client 

int sockfd; FILE *fp; main() { pthread_t tid; fp = fopen( … ); /* Start the usual way */ sockfd = Socket( … ); … Connect( … ); /* Create a thread to send data */ Pthread_create(&tid, NULL, write_func, NULL); /* read data from sockfd */ read_func(); /* wait for child thread */ Pthread_join(tid, NULL); }

void * write_func(void *arg) { char sendline[MAXLINE]; while( more data in fp) Read from fp into sendline[]; Write sendline[] into sockfd; Shutdown(sockfd, SHUT_WR); return(NULL); } void read_func() { char recvline[MAXLINE]; while ( more data from sockfd) Read from sockfd into recvline[]; Write from recvline[] to stdout; }

Locking in Threads

Mutex – for mutual exclusion int counter = 0; void *thread_func(void *arg) { int val; /* unprotected code – why? */ val = counter; counter = val + 1; return NULL; }

Mutex… int counter = 0; ptread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_func(void *arg) { int val; /* protected by mutex */ Pthread_mutex_lock( &mutex ); val = counter; counter = val + 1; Pthread_mutex_unlock( &mutex ); return NULL; }

Condition Variable – for signaling Think of Producer – consumer problem Producers and consumers run in separate threads. Producer produces data and consumer consumes data. Producer has to inform the consumer when data is available Consumer has to inform producer when buffer space is available

Without Condition Variables

/* Globals */ int data_avail = 0; pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; void *producer(void *) { Pthread_mutex_lock(&data_mutex); Produce data Insert data into queue; data_avail=1; Pthread_mutex_unlock(&data_mutex); }

void *consumer(void *) { while( !data_avail ); /* do nothing – keep looping!!*/ Pthread_mutex_lock(&data_mutex); Extract data from queue; if (queue is empty) data_avail = 0; Pthread_mutex_unlock(&data_mutex); consume_data(); }

With Condition Variables

int data_avail = 0; pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cont_t data_cond = PTHREAD_COND_INITIALIZER; void *producer(void *) { Pthread_mutex_lock(&data_mutex); Produce data Insert data into queue; data_avail = 1; Pthread_cond_signal(&data_cond); Pthread_mutex_unlock(&data_mutex); }

void *consumer(void *) { Pthread_mutex_lock(&data_mutex); while( !data_avail ) { /* sleep on condition variable*/ Pthread_cond_wait(&data_cond, &data_mutex); } /* woken up */ Extract data from queue; if (queue is empty) data_avail = 0; Pthread_mutex_unlock(&data_mutex); consume_data(); }