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

Similar documents
pthreads CS449 Fall 2017

Threads. Threads (continued)

CSE 333 SECTION 9. Threads

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

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

CS 3305 Intro to Threads. Lecture 6

CS510 Operating System Foundations. Jonathan Walpole

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

CS333 Intro to Operating Systems. Jonathan Walpole

Concurrency. Johan Montelius KTH

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

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

CSE 306/506 Operating Systems Threads. YoungMin Kwon

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

Introduction to pthreads

LSN 13 Linux Concurrency Mechanisms

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

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

POSIX PTHREADS PROGRAMMING

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

Threads. studykorner.org

CS510 Operating System Foundations. Jonathan Walpole

Multithreaded Programming

CS370 Operating Systems

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

Last class: Today: Thread Background. Thread Systems

CSCE 313: Intro to Computer Systems

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

CS370 Operating Systems

Thread and Synchronization

Threads. lightweight processes

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

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

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

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

CS 261 Fall Mike Lam, Professor. Threads

Threads. CS3026 Operating Systems Lecture 06

CS370 Operating Systems

POSIX Threads. Paolo Burgio

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

Concurrent Programming. Concurrent Programming with Processes and Threads

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Creating Threads. Programming Details. COMP750 Distributed Systems

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

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

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control

Introduction to PThreads and Basic Synchronization

ANSI/IEEE POSIX Standard Thread management

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

CSci 4061 Introduction to Operating Systems. (Thread-Basics)

Lecture 4 Threads. (chapter 4)

real time operating systems course

4. Concurrency via Threads

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

Multithreading. Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4

PThreads in a Nutshell

Chapter 4 Concurrent Programming

ECE 598 Advanced Operating Systems Lecture 23

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Threads. Jo, Heeseung

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

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

CMPSC 311- Introduction to Systems Programming Module: Concurrency

High Performance Computing Course Notes Shared Memory Parallel Programming

CS 326: Operating Systems. Process Execution. Lecture 5

C Grundlagen - Threads

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

Operating Systems & Concurrency: Process Concepts

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

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

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

Operating systems fundamentals - B06

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

Parallel Programming with Threads

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CS370 Operating Systems

THREADS. Jo, Heeseung

Computer Systems Laboratory Sungkyunkwan University

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

CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion:

High Performance Computing Lecture 21. Matthew Jacob Indian Institute of Science

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

Chapter 4: Threads. Operating System Concepts with Java 8 th Edition

Threads. CS-3013 Operating Systems Hugh C. Lauer. CS-3013, C-Term 2012 Threads 1

CS533 Concepts of Operating Systems. Jonathan Walpole

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

Section 4: Threads CS162. September 15, Warmup Hello World Vocabulary 2

POSIX Threads. HUJI Spring 2011

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

Concurrent Programming

Concurrent Programming

Threaded Programming. Lecture 9: Alternatives to OpenMP

Exercise (could be a quiz) Solution. Concurrent Programming. Roadmap. Tevfik Koşar. CSE 421/521 - Operating Systems Fall Lecture - IV Threads

Processes and Threads

4.8 Summary. Practice Exercises

Pthread (9A) Pthread

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

Thread Fundamentals. CSCI 315 Operating Systems Design 1

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012

User Space Multithreading. Computer Science, University of Warwick

Transcription:

CSci 4061 Introduction to Operating Systems (Threads-POSIX)

How do I program them?

General Thread Operations Create/Fork Allocate memory for stack, perform bookkeeping Parent thread creates child threads Associates function to execute Returns an id Destroy/Cancel Release memory (or recycle), perform bookkeeping Suspend (e.g. Sleep) ->blocked Resume->unblock, Yield->deschedule Wait/Join Wait for something, e.g. child finishing

Remember System may time-slice your thread You should assume that a thread could be switched at any time your program should still work A program that fails 1 out of 10^100 runs is buggy This will make your code much more portable

Pthread: Creation Creating a thread is like a combination of fork () and exec () #include <pthread.h> int pthread_create(pthread_t *thread, pthread_attr_t *attr, void * (*function)(void *), void *arg); often NULL (input arg) thread is the returned thread ID, attr is an attribute set function is the function to be called with arg Compile/Link with D_REENTRANT -lpthread

Pthreads: Creation (cont d) The thread stays in the system until its function returns/exits (or it is cancelled/killed) At that point the thread is finished Most POSIX thread calls returns 0 upon success, nonzero otherwise POSIX thread functions return an error code: they do not set errno! Thread states: running, blocked, ready, terminated K ready threads, 1 is running (single core)

Parameters When you start a thread, you pass its function a pointer to an arg void *thread_fn (void *arg) { printf ( %d, *((int *)arg); } arg is a void* so you can cast it to whatever you need when pthread_create () returns thread_fn may not be running.yet void main (){ pthread_t tl; int x = 1; } pthread_create (&tl, NULL, thread_fn,(void*)&x); x = 2;

Thread identity Threads are identified by the value type pthread_t #include <pthread.h> No params pthread_t pthread_self (void); pthread_self () returns the identity of the calling thread int pthread_equal (pthread_t tl, pthread_t t2);

Thread Termination The thread function returns a void* when thread returns/finishes You can also explicitly exit elsewhere #include <pthread.h> void pthread_exit (void *return_value); return and pthread exit are the same, except in the main thread (where return ends the process) exit/abort will terminate the process if called from any thread

Thread Cancellation Cancel a thread when it is a good time to stop done from the outside, e.g. parent make a cancellation request #include <pthread.h> void pthread_cancel (pthread_t thread, NULL); Cancellation can be controlled See pthread_setcancel{state type} pthread_cancelstate (PTHREAD_CANCEL_DISABLE, NULL) Using state, thread can control if it is cancellable (it is, by default) Using type, control when a thread may be cancelled anytime, at a blocking point

Joining threads Joining a thread is analogous to waiting/blocking for a child process to complete #include <pthread.h> int pthread_join (pthread_t th, void **thread_return); thread_return is the exit value of the thread from return or pthread_exit Note: unlike wait()have to name the thread in question For fun, try a pthread_join (pthread_self()) what happened and why?

Yield To yield a thread: gives up the CPU -- HINT int pthread_yield (); Suspend (block)/resume (unblock) Posix doesn t have these explicitly Other thread packages do We can achieve this with synchronization E.g. locks

Pthread example #include <pthread.h> #include <stdio.h> void *pmf (void *msg) { char *message; message = (char*) msg; fprintf (stderr, %s, message); return 0; }

Pthread example (cont d) int main (){ pthread_t t1, t2; char *message1 = Hello ; char *message2 = World ; pthread_create (&tl, NULL, pmf, (void*) message1); pthread_create ((&t2, NULL, pmf, (void*) message2); pthread_join (t1, NULL); // block until t1 finishes pthread_join (t2, NULL); // block until t2 finishes exit (1);} <threadtest>

Parameters What is the problem with this? void main (){ pthread_t tl; int i; for (i=0; i<max; i++) pthread_create (&tl, NULL, thread_fn, (void*)&i); } <threadnum>

Detaching threads #include <pthread.h> int pthread_detach (pthread_t thread); A detached thread cannot be joined it will just go away when it exits You cannot detach a thread if some other thread is joining it Good style and practice: should either detach or join every thread For joinable threads, its resources are not released until join is performed

Thread Implementations POSIX threads are implemented by a userlevel library May be pure user-level Can be exploit kernel threads if available Behavior can vary slightly

POSIX thread safety All threads see the same global environment Thread safety is an issue globals and static data, heap data Any library function that is async-signal-safe is thread-safe see man pages Compile with -D_REENTRANT (just in case)

POSIX thread safety (cont d) Most standard libraries have thread-safe code Variables (even global and static ones) may get moved into the thread context Each thread gets a copy of non-local variables (e.g. errno) Errno: #define errno errno (thread_id) Shared data-structures like heap code (in malloc) are protected by locks

Pthread attributes Things you can change include: Stack size Scheduling attributes

Default policy? Time-slicing

Scheduling Control if time