pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)

Similar documents
CSCE 313: Intro to Computer Systems

CSCE 313 Introduction to Computer Systems. Instructor: Dr. Dezhen Song

CPSC 313: Intro to Computer Systems. POSIX Threads. Latency Hiding / Multiprogramming (covered earlier) Ease of Programming (covered now)

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff

Pthread (9A) Pthread

CS510 Operating System Foundations. Jonathan Walpole

CS333 Intro to Operating Systems. Jonathan Walpole

Threads. studykorner.org

pthreads CS449 Fall 2017

CS510 Operating System Foundations. Jonathan Walpole

CSE 333 SECTION 9. Threads

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source:

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu

Chapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together:

Pthreads: POSIX Threads

CS240: Programming in C. Lecture 18: PThreads

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Threads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr.

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Processes, Threads, SMP, and Microkernels

CSci 4061 Introduction to Operating Systems. (Threads-POSIX)

ANSI/IEEE POSIX Standard Thread management

Threads. Jo, Heeseung

CS Operating Systems: Threads (SGG 4)

CS 5523 Operating Systems: Thread and Implementation

Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai

CS 3305 Intro to Threads. Lecture 6

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017

Thread and Synchronization

Introduction to pthreads

Operating systems fundamentals - B06

Multithreaded Programming

Threads. lightweight processes

About me Now that you know the pthread API

LSN 13 Linux Concurrency Mechanisms

POSIX Threads. HUJI Spring 2011

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology

Threads. Jo, Heeseung

Computer Systems Laboratory Sungkyunkwan University

Threads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή

Last class: Today: Thread Background. Thread Systems

CS370 Operating Systems

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1

Lecture 19: Shared Memory & Synchronization

Concurrent Programming

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

Programming with Shared Memory. Nguyễn Quang Hùng

Modern Computer Architecture. Lecture 10 Multi-Core: pthreads, OpenMP Segmented Scan

Threads. Threads (continued)

CS370 Operating Systems

Total Score is updated. The score of PA4 will be changed! Please check it. Will be changed

Posix Threads (Pthreads)

CS533 Concepts of Operating Systems. Jonathan Walpole

Threads. Today. Next time. Why threads? Thread model & implementation. CPU Scheduling

Threads. To do. Why threads? Thread model & implementation. q q q. q Next time: Synchronization

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process

In the example, since printf() was never declared, the compiler had to try to figure out what kind of function it is.

Topics: Threads (SGG, Chapter 04) (USP, Chapter 12) CS 3733 Operating Systems

real time operating systems course

CS370 Operating Systems

Programming with Shared Memory

Concurrent Programming

POSIX Threads. Paolo Burgio

CS370 Operating Systems

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid.

ECE 598 Advanced Operating Systems Lecture 23

Chapter 4 Concurrent Programming

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001

CSE 306/506 Operating Systems Threads. YoungMin Kwon

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1

Multicore and Multiprocessor Systems: Part I

Multi-threaded Programming

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives

A Thread is an independent stream of instructions that can be schedule to run as such by the OS. Think of a thread as a procedure that runs

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

Overview. Administrative. * HW 2 Grades. * HW 3 Due. Topics: * What are Threads? * Motivating Example : Async. Read() * POSIX Threads

Concurrency. Johan Montelius KTH

Parallelization, OpenMP

Shared Address Space Programming with Pthreads. CS 5334/4390 Spring 2014 Shirley Moore, Instructor February 18, 2014

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

POLITECNICO DI TORINO III Facoltà di Ingegneria dell Informazione INDUSTRIAL NETWORKS AND REAL-TIME OPERATING SYSTEMS.

POSIX PTHREADS PROGRAMMING

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam

POSIX Threads: a first step toward parallel programming. George Bosilca

Programming Languages

Concurrent Programming. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References

Concurrent Programming

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

Concurrent Programming. Concurrent Programming with Processes and Threads

Lecture 4 Threads. (chapter 4)

Introduction to Threads

Transcription:

pthreads 1 Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 2 1

Thread Packages Kernel thread packages Implemented and supported at kernel level User-level thread packages Implemented at user level 3 Implementing Threads in User Space (Old Linux) A user-level threads package 4 2

User-level Threads 5 User-level Threads Advantages Fast Context Switching: User level threads are implemented using user level thread libraries, rather than system calls, hence no call to OS and no interrupts to kernel When a thread is finished running for the moment, it can call thread_yield. This instruction (a) saves the thread information in the thread table, and (b) calls the thread scheduler to pick another thread to run. The procedure that saves the local thread state and the scheduler are local procedures, hence no trap to kernel, no context switch, no memory switch, and this makes the thread scheduling very fast. Customized Scheduling 6 3

Kernel-level Threads Kernel can schedule threads in addition to processes. Multiple threads of a process can run simultaneously on multiple CPUs. Synchronization more efficient than for processes (but less than for user-level threads). Kernel-level threads can make blocking I/O calls without blocking other threads of same process 7 Trade-offs? Kernel thread packages Each thread can make blocking I/O calls Can run concurrently on multiple processors Threads in User-level Fast context switch Customized scheduling 8 4

Hybrid Implementations (Solaris) Multiplexing user-level threads onto kernel-level threads 9 Pthread Operations (review) POSIX function pthread_cancel pthread_create pthread_detach pthread_equal pthread_exit pthread_kill pthread_join pthread_self description terminate another thread create a thread set thread to release resources test two thread IDs for equality exit a thread without exiting process send a signal to a thread wait for a thread find out own thread ID 10 5

Creating a Thread When a new thread is created it runs concurrently with the creating process. When creating a thread you indicate which function the thread should execute. 11 Creating a thread with pthread A thread is created with int pthread_create( pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg); The creating process (or thread) must provide a location for storage of the thread id. The third parameter is just the name of the function for the thread to run. The last parameter is a pointer to the arguments. 12 6

The Restrict Keyword One of the new features in the recently approved C standard C99 This qualifier can be applied to a data pointer to indicate that During the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer. It enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer Can avoid pointer aliasing problem 13 Example 1: Thread Creation #include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf("hello World! It's me, thread #%d!\n", tid); pthread_exit(null); int main (int argc, char *argv[]) { pthread_t threads[num_threads]; int rc, t; for(t=0; t<num_threads; t++){ printf("in main: creating thread %d\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc) { printf("error code is %d\n", rc); exit(-1); pthread_exit(null); 14 7

Example 2: Passing Parameters to a Thread #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 5 void *PrintHello(void *ptr) { char *filename; int j; filename = (char *) ptr; while (1) { printf("hello World! It's me, thread %s!\n", filename); for (j=1; j++; j<500); pthread_exit(null); 15 Example 2: Passing Parameters to a Thread int main (int argc, char *argv[]) { pthread_t thread[100]; int err_code, i=0; char *filename; printf ("Enter thread name at any time to create thread\n"); while (1) { filename = (char *) malloc (80*sizeof(char)); scanf ("%s", filename); printf("in main: creating thread %d\n", i); err_code = pthread_create(&thread[i], NULL, PrintHello, (void *)filename); if (err_code){ printf("error code is %d\n", err_code); exit(-1); else i++; pthread_exit(null); 16 8

Example 3: Files void *PrintHello(void *ptr) { FILE *file; char *filename; char textline[100]; int j; filename = (char *) ptr; printf("hello World! Opening %s!\n", filename); file = fopen(filename, "r"); if (file!= NULL) { while(fscanf(file, "%s\n", textline)!= EOF) printf ("%s\n", textline); fclose(file); 17 Exiting and Cancellation Question: If a thread calls exit(), what about other threads in the same process? When does a process terminate? 18 9

Exiting and Cancellation Question: If a thread calls exit(), what about other threads in the same process? A process can terminate when: it calls exit directly one of its threads calls exit it returns from main() it receives a termination signal In any of these cases, all threads of the process terminate. 19 Thread Exit When a thread is done, it can return from its first function (the one used by pthread_create) or it can call pthread_exit void pthread_exit(void *value_ptr); Common uses: Return value is often a pointer to the original struct or a malloc d struct (memory must be free d by joining thread) Use the heap not the stack!!! 20 10

Cancel that thread! One thread can request that another exit with pthread_cancel int pthread_cancel(pthread_t thread); The pthread_cancel returns after making the request. 21 Thread Attributes Create an attribute object (initialize it with default properties) Modify the properties of the attribute object Create a thread using the attribute object The object can be changed or reused without affecting the thread The attribute object affects the thread only at the time of thread creation 22 11

Settable Properties of Thread Attributes property attribute objects detach state stack scheduling function pthread_attr_destroy pthread_attr_init pthread_attr_getdetachstate pthread_attr_setdetachstate pthread_attr_getguardsize pthread_attr_setguardsize pthread_attr_getstack pthread_attr_setstack pthread_attr_getinheritsched pthread_attr_setinheritsched pthread_attr_getschedparam pthread_attr_setschedparam pthread_attr_getschedpolicy pthread_attr_setschedpolicy pthread_attr_getscope pthread_attr_setscope 23 Example: Create a detached thread int e, fd; pthread_attr_t tattr; pthread_t tid; if(e = pthread_attr_init(&tattr)) fprintf(stderr, "Failed to create attribute object: %s\n", strerror(e)); else if(e = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED)) fprintf(stderr, "Failed to set attribute state to detached: %s\n", strerror(e)); else if(e = pthread_create(&tid, &tattr, data, &fd)) fprintf(stderr, "Failed to create thread: %s\n", strerror(e)); 24 12

Zombies, Thread Detach & Join Call pthread_join() or pthread_detach() for every thread that is created joinable so that the system can reclaim all resources associated with the thread Failure to join or to detach threads memory and other resource leaks until the process ends 25 Detaching a Thread int pthread_detach(pthread_t threadid); Indicate that system resources for the specified thread should be reclaimed when the thread ends If the thread is already ended, resources are reclaimed immediately This routine does not cause the thread to end A detached thread s thread ID is undetermined Threads are detached after a pthread_detach() call after a pthread_join() call if a thread terminates and the PTHREAD_CREATE_DETACHED attribute was set on creation 26 13

How to make a Thread Detached void *processfd(void *arg); int error; int fd pthread_t tid; if (error = pthread_create(&tid, NULL, processfd, &fd)) { fprintf(stderr, "Failed to create thread: %s\n", strerror(error)); else if (error = pthread_detach(tid)){ fprintf(stderr, "Failed to detach thread: %s\n", strerror(error)); 27 How a thread can detach itself void *runnger(void *arg) { if (!pthread_detach( pthread_self()) ) return NULL; 28 14

Waiting on a Thread: pthread_join() int pthread_join(pthread_t thread, void** retval); pthread_join() is a blocking call on nondetached threads It indicates that the caller wishes to block until the thread being joined exits You cannot join on a detached thread, only non-detached threads (detaching means you are NOT interested in knowing about the threads exit) 29 Pthread_join int error; int *exitcodep; pthread_t tid; if (error = pthread_join(tid, &exitcodep)){ fprintf(stderr, "Failed to join thread: %s\n", strerror(error)); else { fprintf(stderr, "The exit code was %d\n", *exitcodep); 30 15

Thread scheduling int pthread_attr_getscope(const pthread_attr_t *restrict attr, int *restrict contentionscope); int pthread_attr_setscope(pthread_attr_t *attr, int contentionscope); The contentionscope can be PTHREAD_SCOPE_PROCESS or PTHREAD_SCOPE_SYSTEM. The scope determines whether the thread competes with other threads of the process or with other processes in the system. 31 Create a thread that contends with other processes pthread_attr_init(&tattr)) pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM)) thread_create(&tid, &tattr, myfunction, &myptr)) 32 16