Programming with Threads. Threads  Sometimes called a lightweight process  smaller execution unit than a process  Consists of:  program counter 

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

Threads. Readings r Silberschatz et al : Chapter 4.
Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Sockets. Socket Berkeley Software Distribution Handle-like data structure for communicating A socket is an endpoint  Send and receive  Attach a protocol.
Day 10 Threads. Threads and Processes  Process is seen as two entities Unit of resource allocation (process or task) Unit of dispatch or scheduling (thread.
Lecture 4: Concurrency and Threads CS 170 T Yang, 2015 Chapter 4 of AD textbook.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
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. Processes and Threads  Two characteristics of “processes” as considered so far: Unit of resource allocation Unit of dispatch  Characteristics.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
CS 3013 & CS 502 Summer 2006 Threads1 CS-3013 & CS-502 Summer 2006.
Threads Chapter 4. Modern Process & Thread –Process is an infrastructure in which execution takes place  (address space + resources) –Thread is a program.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads.
Operating Systems Chapter 5 Threads. Benefits Responsiveness Resource Sharing Economy Utilization of MP Architectures.
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.
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.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
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,
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.
Linux Programming –Threads CS Threads Review Threads in the same address space –share everything in the address space –lighter than process –no.
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
Programming Shared Address Space Platforms Carl Tropper Department of Computer Science.
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.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Chapter 4: Threads Overview Multithreading.
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
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.
P4: Multithreaded Programming Zhenxiao Luo CS537 Spring 2010.
Silberschatz, Galvin and Gagne ©2005 Modified by Dimitris Margaritis, Spring 2007 Chapter 4: Threads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
CS307 Operating Systems Threads Fan Wu Department of Computer Science and Engineering Shanghai Jiao Tong University Spring 2011.
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
Threads A thread is an alternative model of program execution
Announcements. Cooperating Processes  Operating systems allow for the creation and concurrent execution of multiple processes & threads  eases program.
NCHU System & Network Lab Lab #6 Thread Management Operating System Lab.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
2.2 Threads  Process: address space + code execution  There is no law that states that a process cannot have more than one “line” of execution.  Threads:
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
COMP7330/7336 Advanced Parallel and Distributed Computing POSIX Thread API Dr. Xiao Qin Auburn University
回到第一頁 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.
COMP7330/7336 Advanced Parallel and Distributed Computing POSIX Thread API Dr. Xiao Qin Auburn University
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.
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
PThreads.
Threads in C Caryl Rahn.
Shared-Memory Programming with Threads
Threads Threads.
Boost String API & Threads
Auburn University COMP7330/7336 Advanced Parallel and Distributed Computing Pthread Mutex Dr. Xiao Qin Auburn University.
Thread Programming.
Chapter 4: Threads.
Linux Processes & Threads
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Thread Programming.
Operating System Concepts
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using Posix Threads (pthreads)
Tutorial 4.
POSIX Threads(pthreads)
Presentation transcript:

Programming with Threads

Threads  Sometimes called a lightweight process  smaller execution unit than a process  Consists of:  program counter  register set  stack space  Threads share:  memory space  code section  OS resources(open files, signals, etc.)  Sometimes called a lightweight process  smaller execution unit than a process  Consists of:  program counter  register set  stack space  Threads share:  memory space  code section  OS resources(open files, signals, etc.)

Threads  A process is defined to have at least one thread of execution  A process may launch other threads which execute concurrently with the process  Switching between threads is faster  No memory management issues, etc.  Mutual exclusion problems:  A process is defined to have at least one thread of execution  A process may launch other threads which execute concurrently with the process  Switching between threads is faster  No memory management issues, etc.  Mutual exclusion problems:

Threads Process 0 code mem regs Process 1 code mem regs All threads in a process share the same memory space

Single Threaded and Multithreaded Process Models Thread Control Block User Stack User Stack Kernel Stack Kernel Stack User Address Space User Address Space Process Control Block Process Control Block Thread Single-Threaded Process Model Multithreaded Process Model Thread Control Block User Stack Kernel Stack Thread Control Block User Stack Kernel Stack Thread

Why Threads?  Software Portability  Latency Hiding  Scheduling and Load Balancing  Speed  Ease of Programming and Widespread use  Program Maintenance  Software Portability  Latency Hiding  Scheduling and Load Balancing  Speed  Ease of Programming and Widespread use  Program Maintenance

Thread issues  How should threads be scheduled compared to processes?  Equal to processes  Within the parent processes quantum  How are threads implemented  kernel support (system calls)  user level threads  What are the issues?  How should threads be scheduled compared to processes?  Equal to processes  Within the parent processes quantum  How are threads implemented  kernel support (system calls)  user level threads  What are the issues?

User-Level Threads  All thread management is done by the application  The kernel is not aware of the existence of threads  Thread switching does not require kernel mode privileges  Scheduling is application specific  All thread management is done by the application  The kernel is not aware of the existence of threads  Thread switching does not require kernel mode privileges  Scheduling is application specific

Kernel-Level Threads  Windows NT and Linux are examples of this approach  Kernel maintains context information for the process and the threads  Switching between threads requires the kernel  Windows NT and Linux are examples of this approach  Kernel maintains context information for the process and the threads  Switching between threads requires the kernel

POSIX Threads  Thread API available on many OS’s  #include  cc myprog.c –o myprog -lpthread  Thread creation  int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);  Thread termination  void pthread_exit(void *retval);  Waiting for Threads  int pthread_join(pthread_t th, void **thread_return);  Thread API available on many OS’s  #include  cc myprog.c –o myprog -lpthread  Thread creation  int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);  Thread termination  void pthread_exit(void *retval);  Waiting for Threads  int pthread_join(pthread_t th, void **thread_return);

#include int print_message_function( void *ptr ); int x = 1; main() { pthread_t thread1, thread2; int thread1result, thread2result; char *message1 = "Hello"; char *message2 = "World"; pthread_attr_t *pthread_attr_default = NULL; printf("Begin\n"); pthread_create( &thread1, pthread_attr_default, (void*)&print_message_function, (void*) message1); pthread_create(&thread2, pthread_attr_default, (void*)&print_message_function, (void*) message2); pthread_join(thread1, (void *)&thread1result); printf("End thread1 with %d\n", thread1result); pthread_join(thread2, (void *)&thread2result); printf("End thread2 with %d\n", thread2result); exit(0); } int print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf("%s ", message); fflush(stdout); return x++; }

#include server() { SOCKET listenSkt, newSkt; struct sockaddr_in serverName, clientName; listenSkt = socket(AF_INET, SOCK_STREAM, 0); //Fill in serverName bind(listenSkt, &serverName, sizeof(serverName)); listen(listenSkt, 5); newSkt = accept(listenSkt, &clientName, sizeof(clientName)); // Fire off a thread to do communication using send and recv on newSkt // Loop back and accept another connection close(skt); } #include server() { SOCKET listenSkt, newSkt; struct sockaddr_in serverName, clientName; listenSkt = socket(AF_INET, SOCK_STREAM, 0); //Fill in serverName bind(listenSkt, &serverName, sizeof(serverName)); listen(listenSkt, 5); newSkt = accept(listenSkt, &clientName, sizeof(clientName)); // Fire off a thread to do communication using send and recv on newSkt // Loop back and accept another connection close(skt); }

typedef struct myarg { int skt; int whatever; }MyArg; … pthread_attr_t *default = NULL; MyArg *arg; while (!done) { newSkt = accept(listenSkt, &clientName, sizeof(clientName)); // Allocate and fill the argument structure arg = (MyArg *)malloc(sizeof(MyArg)); arg->skt = newSkt; // Fire off a thread to do communication using send and recv on newSkt pthread_create(&threads[j], default, HandleConnection, (void *)arg); } typedef struct myarg { int skt; int whatever; }MyArg; … pthread_attr_t *default = NULL; MyArg *arg; while (!done) { newSkt = accept(listenSkt, &clientName, sizeof(clientName)); // Allocate and fill the argument structure arg = (MyArg *)malloc(sizeof(MyArg)); arg->skt = newSkt; // Fire off a thread to do communication using send and recv on newSkt pthread_create(&threads[j], default, HandleConnection, (void *)arg); }

typedef struct myarg { int skt; int whatever; }MyArg; … void *HandleConnection(void *arg) { int skt; char buffer[255]; // Don’t do this!!!! Allocate as much as you need! skt = (MyArg *)arg->skt; recv(skt, buffer, bufflen, 0);// Wrap this in a while loop // Process the message send(skt, response, responselength, 0); } typedef struct myarg { int skt; int whatever; }MyArg; … void *HandleConnection(void *arg) { int skt; char buffer[255]; // Don’t do this!!!! Allocate as much as you need! skt = (MyArg *)arg->skt; recv(skt, buffer, bufflen, 0);// Wrap this in a while loop // Process the message send(skt, response, responselength, 0); }

Thread Issues  Thread function only gets  One void * argument and void * return  How do you do more?  Reentrance  False Sharing  Not same global variable, but within cache line  Mutual Exclusion  Thread function only gets  One void * argument and void * return  How do you do more?  Reentrance  False Sharing  Not same global variable, but within cache line  Mutual Exclusion

Effects of False Sharing Multiple Threads Writing to two variables Placement local stack variables Right next to each other 16 words apart 32 words apart Multiple Threads Writing to two variables Placement local stack variables Right next to each other 16 words apart 32 words apart Local variables Shared variables In Same Cache Line

Synchronization Primitives  int pthread_mutex_init( pthread_mutex_t *mutex_lock, const pthread_mutexattr_t *lock_attr);  int pthread_mutex_lock( pthread_mutex_t *mutex_lock);  int pthread_mutex_unlock( pthread_mutex_t *mutex_lock);  int pthread_mutex_trylock( pthread_mutex_t *mutex_lock);  int pthread_mutex_init( pthread_mutex_t *mutex_lock, const pthread_mutexattr_t *lock_attr);  int pthread_mutex_lock( pthread_mutex_t *mutex_lock);  int pthread_mutex_unlock( pthread_mutex_t *mutex_lock);  int pthread_mutex_trylock( pthread_mutex_t *mutex_lock);

#include void *find_min(void *list_ptr) pthread_mutex_t minimum_value_lock; int minimum_value, partial_list_size; main(){ minimum_value = MIN_INT; pthread_init(); pthread_mutex_init(&minimum_value_lock, NULL); /*inititalize lists etc, create and join threads*/ } void *find_min(void *list_ptr){ int *partial_list_ptr, my_min = MIN_INT, i; partial_list_ptr = (int *)list_ptr; for (i = 0; i < partial_list_size; i++) if (partial_list_ptr[i] < my_min) my_min = partial_list_ptr[i]; pthread_mutex_lock(minimum_value_lock); if (my_min < minimum_value) minimum_value = my_min; pthread_mutex_unlock(minimum_value_lock); pthread_exit(0); }

Locking Overhead  Serialization points  Minimize the size of critical sections  Be careful  Rather than wait, check if lock is available  Pthread_mutex_trylock  If already locked, will return EBUSY  Will require restructuring of code  Serialization points  Minimize the size of critical sections  Be careful  Rather than wait, check if lock is available  Pthread_mutex_trylock  If already locked, will return EBUSY  Will require restructuring of code

/* Finding k matches in a list */ void *find_entries(void *start_pointer) { /* This is the thread function */ struct database_record *next_record; int count; current_pointer = start_pointer; do { next_record = find_next_entry(current_pointer); count = output_record(next_record); } while (count < requested_number_of_records); } int output_record(struct database_record *record_ptr) { int count; pthread_mutex_lock(&output_count_lock); output_count ++; count = output_count; pthread_mutex_unlock(&output_count_lock); if (count <= requested_number_of_records) print_record(record_ptr); return (count); }

/* rewritten output_record function */ int output_record(struct database_record *record_ptr) { int count; int lock_status; lock_status=pthread_mutex_trylock(&output_count_lock); if (lock_status == EBUSY) { insert_into_local_list(record_ptr); return(0); } else { count = output_count; output_count += number_on_local_list + 1; pthread_mutex_unlock(&output_count_lock); print_records(record_ptr, local_list, requested_number_of_records - count); return(count + number_on_local_list + 1); }