Operating Systems. Practical Session 4 Threads

Size: px
Start display at page:

Download "Operating Systems. Practical Session 4 Threads"

Transcription

1 Operating Systems Practical Session 4 Threads 1

2 Threads Executed within a process. Allow multiple independent executions under the same process (container). Possible states: running, ready, blocked, terminated. In most of today s operating systems, a process is created with at least one thread but may have more than one thread (multithreading). 2

3 Threads - Advantages Share open files, data structures, global variables, child processes, etc. Peer threads can communicate without using System calls. Threads are faster to create/terminate/switch than processes (have no resources attached). Parallelism which improves overall performance: A single core CPU and a substantial amount of computing and I/O Multiple cores 3

4 Threads - Disadvantages Share open files, data structures, global variables, child processes, etc. No protection between threads one can read/write/wipe out/corrupt the other s data. Sending some signals (such as SIGSTOP) to a process affects all threads running within it. 4

5 Threads vs. Processes ( classic approach Linux s clone results in some ambiguity) Processes unique open I/O unique signal table unique stack unique PC unique registers unique state heavy context switch Threads shared open I/O shared signal table unique stack unique PC unique registers unique state light context switch Notice, signal handlers must be shared among all threads of a multithreaded application. 5

6 Threads - motivation Dispatcher thread: while (TRUE) { get_next_request(&buf); handoff_work(&buf); Dispatcher Worker thread: while (TRUE) { wait_for_work(&buf); look_for_page_in_cache(&buf, &page); if (page_not_in_cache(&page)) read_page_from_disk(&buf, &page); return page(&page); Webpage request Web page cache Why are threads better in this case? Such communication requires a shared memory Workers Example from Modern Operating Systems, 2 nd 6 Edition, pg. 88

7 Threads some known Issues Does the fork() command duplicate just the calling thread or all threads of the process? POSIX defines that only the calling thread is replicated in the child process. Solaris 10 defines fork1() and forkall() which attempt to better define the relation between fork and threads, however, this is not POSIX compliant. Many issues arise from using fork in a multithreaded code. Unless calling exec immediately after fork, try to avoid it! Does the exec() command replace the entire process? The entire process is replaced including all its threads. 7

8 User-level and Kernel-level Threads Threads Library User space Kernel space User space Kernel space P P (a) Pure user-level (b) Pure kernel-level 8

9 User-level and Kernel-level Threads Threads Library User space Kernel space P P (c) Combined Source: Stallings, Operating Systems: Internals and design principles 7 th ed. 9

10 User-level threads The kernel sees just the main thread of the process (all other threads that run within the process context are invisible to the OS). The user application not the kernel is responsible for scheduling CPU time for its internal threads within the running time scheduled for it by the kernel. 10

11 User-level threads (cont d) User-level threads implement in user-level libraries, rather than via systems calls, so thread switching does not need to call operating system and to cause interrupt to the kernel. The kernel s inability to distinguish between user level threads makes it difficult to design preemptive scheduling. If a thread makes a blocking system call, the entire process is blocked. Will only utilize a single CPU. 11

12 Kernel-level threads All threads are visible to the kernel. The kernel manages the threads. The kernel schedules each thread within the time-slice of each process. The user cannot define the scheduling policy. Context switching is slower for kernel threads than for user-level threads. Because the kernel is aware of the threads, in multiple CPU machines, each CPU can run a different thread of the same process, at the same time. 12

13 User-level vs. kernel-level threads Threads Scheduling policy Thread switching Context switch Blocking calls Thread table User-level threads Invisible to the kernel User defined Non-preemptive * Faster, done by the runtime Block the whole process Held by the process Kernel-level threads Visible to the kernel Kernel defined Preemptive Slower, done by the kernel Block the single thread Held by the kernel 13

14 A tech. note on POSIX threads When the first Unix and POSIX functions were designed, it was assumed that there will be a single thread of execution. Hence, the need for reentrant functions. Reentrant functions are safe to call before a previous call has finished (usually using only local variables or locking mechanisms) While this is supported by many standard functions, the compiler must be aware of the need for re-entrant functions: gcc D_REENTRANT lpthread 14

15 Threads in POSIX (pthreads) int pthread_create( pthread_t* thread, pthread_attr_t* attr, void* (*start_func)(void*), void* arg) Creates a new thread of control that executes concurrently with the calling thread. The identifier of the newly created thread is stored in the location pointed by the thread argument, and a 0 is returned. attr specifies thread attributes that will be applied to the new thread (e.g. detached, scheduling-policy). Can be NULL (default attributes). start_func is pointer to the function the thread will start executing; arg contains parameter to the funtion func. Thread type is platform-specific pthread_t pthread_self() return this thread s identifier. 15

16 Threads in POSIX (pthreads) cont d int pthread_join( pthread_t th, void** thread_return ) Suspends the execution of the calling thread until the thread identified by th terminates. th is the identifier of the thread that needs to be waited for. At most one thread can wait for the termination of a given thread. The return value of th is stored in the location pointed by thread_return void pthread_exit( void* ret_val ) Terminates the execution of the calling thread. Doesn t terminate the whole process if called from the main function. If ret_val is not null, then ret_val is saved, and its value is given to the thread who performed join on this thread; that is, it will be written to the thread_return parameter in the pthread_join call. 16

17 Hello World! #include <pthread.h> #include <stdio.h> void *printme() { printf("hello World!\n"); return NULL; When compiling a multi-threaded app: gcc D_REENTRANT o myprog myprog.c lpthread void main() { pthread_t tcb; void *status; if (pthread_create(&tcb, NULL, printme, NULL)!= 0) { perror("pthread_create"); exit(1); if (pthread_join(tcb, &status)!= 0) { perror("pthread_join"); exit(1); What can happen if we remove the join part? 17

18 Example A Version 1 void *printme(void *id) { int *i; i = (int *)id; printf("hi. I'm thread %d\n", *i); return NULL; void main() { int i, vals[4]; pthread_t tids[4]; void *retval; for (i = 0; i < 4; i++) { vals[i] = i; pthread_create(tids+i, NULL, printme, vals+i); for (i = 0; i < 4; i++) { printf("trying to join with tid%d\n", i); pthread_join(tids[i], &retval); printf("joined with tid%d\n", i); 18

19 Example A Version 1 possible output Trying to join with tid0 Hi. I'm thread 0 Hi. I'm thread 1 Hi. I'm thread 2 Hi. I'm thread 3 Joined with tid0 Trying to join with tid1 Joined with tid1 Trying to join with tid2 Joined with tid2 Trying to join with tid3 Joined with tid3 19

20 Example A Version 2 void *printme(void *id) { int *i; i = (int *)id; printf("hi. I'm thread %d\n", *i); pthread_exit(null); void main() { int i, vals[4]; pthread_t tids[4]; void *retval; for (i = 0; i < 4; i++) { vals[i] = i; pthread_create(tids+i, NULL, printme, vals+i); for (i = 0; i < 4; i++) { printf("trying to join with tid%d\n", i); pthread_join(tids[i], &retval); printf("joined with tid%d\n", i); pthread_exit(null); 20

21 Example A Version 2 possible output Trying to join with tid0 Hi. I'm thread 0 Hi. I'm thread 1 Hi. I'm thread 2 Hi. I'm thread 3 Joined with tid0 Trying to join with tid1 Joined with tid1 Trying to join with tid2 Joined with tid2 Trying to join with tid3 Joined with tid3 21

22 Example A Version 3 void *printme(void *id) { int *i; i = (int *)id; printf("hi. I'm thread %d\n", *i); pthread_exit(null); void main() { int i, vals[4]; pthread_t tids[4]; void *retval; for (i = 0; i < 4; i++) { vals[i] = i; pthread_create(tids+i, NULL, printme, vals+i); pthread_exit(null); for (i = 0; i < 4; i++) { printf("trying to join with tid%d\n", i); pthread_join(tids[i], &retval); printf("joined with tid%d\n", i); 22

23 Example A Version 3 output Hi. I'm thread 0 Hi. I'm thread 1 Hi. I'm thread 2 Hi. I'm thread 3 If the main thread calls pthread_exit(), the process will continue executing until the last thread terminates or the whole process is terminated 23

24 Example A Version 4 void *printme(void *id) { int *i = (int *)id; sleep(5); printf("hi. I'm thread %d\n", *i); pthread_exit(null); int main() { int i, vals[4]; pthread_t tids[4]; void *retval; for (i = 0; i < 4; i++) { vals[i] = i; pthread_create(tids+i, NULL, printme, vals+i); return 0; 24

25 Example A Version 4 possible output No Output! 25

26 Example A Version 5 void *printme(void *id) { int *i; i = (int *)id; printf("hi. I'm thread %d\n", *i); exit(0); main() { int i, vals[4]; pthread_t tids[4]; void *retval; for (i = 0; i < 4; i++) { vals[i] = i; pthread_create(tids+i, NULL, printme, vals+i); for (i = 0; i < 4; i++) { printf("trying to join with tid%d\n", i); pthread_join(tids[i], &retval); printf("joined with tid%d\n", i); pthread_exit(null); 26

27 Example A Version 5 possible output Trying to join with tid0 Hi. I'm thread 0 27

28 א) Midterm 2006 בעץ תהליכים כל קודקוד מייצג תהליך. קודקוד g מצביע על q. יצר את g כלומר אם q, הוא אבא של g אם"ם q g קודקוד q ) שרטטו את עץ התהליכים הנוצר ע"י הרצת הקוד הבא בשפת C. )תנו שמות 1. int x; שרירותיים לתהליכים הנוצרים.( 2. fork(); 3. x = fork(); 4. if(x!= 0) 6. fork(); 7. printf) pid= %d,getpid()); 28

29 Midterm 2006 (cont d) )א(: פתרון

30 Midterm 2006 (cont d) ב. מהו הפלט של הרצת התוכנית מסעיף א'? האם זהו הפלט היחיד האפשרי? הסבירו. )עד 3 שורות(. פתרון )ב(: שישה מספרים גדולים מ 0. הפלט אינו יחיד, מספרים נכונים. כל שישה ג. אם בין שורות 4 ו 6 נוסיף את השורה: SIGINT);.5 kill(x, מה ישתנה בעץ התהליכים ובפלט? פתרון )ג(: התהליכים 3 ו 4 ימותו. הפלט עשוי להישאר שיודפסו רק 5 מספרים או רק 4 מספרים. זהה או 30

31 Midterm 2006 (cont d) ד. האם ייתכן תסריט שבו לאחר השינוי נקבל פלט זהה לפלט אותו קיבלנו לפני השינוי? אם כן, מהו תסריט זה? אם לא, נמקו מדוע לא יתכן כי נקבל פלט זהה. )ד(: פתרון כן, יתכן כזה תסריט. נניח שהמתזמן נותן לכל בן שנוצר ב- fork לרוץ עד אשר הוא מסיים, הרי שכל אחד יספיק להגיע לשורת ההדפסה. 31

32 Midterm 2006 (cont d) 32 ה. נניח כי תידרשו לכתוב תוכנית מרובת,threads שתרוץ על מערכת הפעלה התומכת גם ב- threads user וגם ב- threads.kernel באיזו אפשרות תבחרו אם ה- threads מבצעים פעולות I/O רבות? הסבירו )עד 3 שורות(. הסבירו באילו נסיבות )כלומר, עבור איזה סוג תוכנית( הייתם בוחרים באפשרות השנייה. פתרון )ה(: פעולת I/O גורמת ל user threads כולם לעבור ל blocking שכן מערכת ההפעלה לא מודעת לקיומם ולכן לא סביר לבחור באופציה זו במקרה של ריבוי פעולות.I/O לעומת זאת, כדאי לבחור ב user threads במקרים בהם רוצים למשל שליטה מלאה על התזמון. בנוסף, אם מדובר במערכת עם יחסית מעט מעבדים נעדיף user threads שכן החלפה ביניהם היא מהירה יותר.

33 Thread-specific data Programs often need global or static variables that have different values in different threads: Thread-specific data (TSD). Each thread possesses a private memory block, the TSD area. This area is indexed by TSD keys (Map). TSD keys are common to all threads, but the value associated with a given TSD key can be different in each thread. Defined in POSIX. 33

34 Thread-specific data (cont d) Question: Why can t we achieve this by using regular variables? Because threads share one memory space. Usage examples: Separate log for each thread. 34

35 Thread-specific data (cont d) int pthread_key_create(pthread_key_t* key, void (*destr_func)(void*)) Allocates a new TSD key. Return 0 on success and a non-zero error code on failure. key the key is stored in the location pointed to by key. destr_func if not NULL, specifies a destructor function associated with the key. When a thread terminates via pthread_exit, destr_func is called with arguments the value associated with the key in that thread. The order in which destructor functions are called at thread termination time is unspecified. int pthread_key_delete(pthread_key_t key) Deallocates a TSD key. Return 0 on success and a non-zero error code on failure. It does not check whether non-null values are associated with that key in the currently executing threads, nor call the destructor function associated with the key. key the key of the value to delete. 35

36 Thread-specific data (cont d) int pthread_setspecific(pthread_key_t key, const void* pointer) Changes the value associated with key in the calling thread, storing the given pointer instead. void* pthread_getspecific(pthread_key_t key) Returns the value currently associated with key in the calling thread, or NULL on error. 36

37 TSD Usage example Suppose, for instance, that your application divides a task among multiple threads. For audit purposes, each thread is to have a separate log file, in which progress messages for that thread's tasks are recorded. The thread-specific data area is a convenient place to store the file pointer for the log file for each individual thread. 37

38 #include <malloc.h> #include <pthread.h> #include <stdio.h> // The key used to associate a log file pointer with each thread. static pthread_key_t thread_log_key; // Write MESSAGE to the log file for the current thread. void write_to_thread_log(const char* message) { FILE* thread_log = (FILE*)pthread_getspecific (thread_log_key); fprintf(thread_log, "%s\n", message); // Close the log file pointer THREAD_LOG. void close_thread_log (void* thread_log) { fclose((file*) thread_log); 38

39 void* thread_function (void* args) { char thread_log_filename[20]; FILE* thread_log; sprintf(thread_log_filename,"thread%d.log",(int) pthread_self()); thread_log = fopen (thread_log_filename, "w"); pthread_setspecific (thread_log_key, thread_log); write_to_thread_log ("Thread starting."); /* Do work here... */ return NULL; int main () { int i; pthread_t threads[5]; pthread_key_create (&thread_log_key, close_thread_log); for (i = 0; i < 5; ++i) pthread_create (&(threads[i]), NULL, thread_function, NULL); for (i = 0; i < 5; ++i) pthread_join (threads[i], NULL); return 0; 39

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

CSci 4061 Introduction to Operating Systems. (Threads-POSIX) 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

More information

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

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff POSIX threads CS 241 February 17, 2012 Copyright University of Illinois CS 241 Staff 1 Recall: Why threads over processes? Creating a new process can be expensive Time A call into the operating system

More information

Threads. Threads (continued)

Threads. Threads (continued) Threads A thread is an alternative model of program execution A process creates a thread through a system call Thread operates within process context Use of threads effectively splits the process state

More information

pthreads CS449 Fall 2017

pthreads CS449 Fall 2017 pthreads CS449 Fall 2017 POSIX Portable Operating System Interface Standard interface between OS and program UNIX-derived OSes mostly follow POSIX Linux, macos, Android, etc. Windows requires separate

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole The Process Concept 2 The Process Concept Process a program in execution Program - description of how to perform an activity instructions and static

More information

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

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu CPSC 341 OS & Networks Threads Dr. Yingwu Zhu Processes Recall that a process includes many things An address space (defining all the code and data pages) OS resources (e.g., open files) and accounting

More information

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Threads Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Concurrency

More information

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

Chapter 10. Threads. OS Processes: Control and Resources. A process as managed by the operating system groups together: SFWR ENG 3BB4 Software Design 3 Concurrent System Design 2 SFWR ENG 3BB4 Software Design 3 Concurrent System Design 10.11 13 OS Processes: Control and Resources Chapter 10 Threads A process as managed

More information

CS 3305 Intro to Threads. Lecture 6

CS 3305 Intro to Threads. Lecture 6 CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform

More information

CS333 Intro to Operating Systems. Jonathan Walpole

CS333 Intro to Operating Systems. Jonathan Walpole CS333 Intro to Operating Systems Jonathan Walpole Threads & Concurrency 2 Threads Processes have the following components: - an address space - a collection of operating system state - a CPU context or

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

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

Threads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits CS307 What is a thread? Threads A thread is a basic unit of CPU utilization contains a thread ID, a program counter, a register set, and a stack shares with other threads belonging to the same process

More information

Threads. studykorner.org

Threads. studykorner.org Threads Thread Subpart of a process Basic unit of CPU utilization Smallest set of programmed instructions, can be managed independently by OS No independent existence (process dependent) Light Weight Process

More information

CSE 306/506 Operating Systems Threads. YoungMin Kwon

CSE 306/506 Operating Systems Threads. YoungMin Kwon CSE 306/506 Operating Systems Threads YoungMin Kwon Processes and Threads Two characteristics of a process Resource ownership Virtual address space (program, data, stack, PCB ) Main memory, I/O devices,

More information

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

Exercise (could be a quiz) Solution. Concurrent Programming. Roadmap. Tevfik Koşar. CSE 421/521 - Operating Systems Fall Lecture - IV Threads Exercise (could be a quiz) 1 2 Solution CSE 421/521 - Operating Systems Fall 2013 Lecture - IV Threads Tevfik Koşar 3 University at Buffalo September 12 th, 2013 4 Roadmap Threads Why do we need them?

More information

Lecture 4 Threads. (chapter 4)

Lecture 4 Threads. (chapter 4) Bilkent University Department of Computer Engineering CS342 Operating Systems Lecture 4 Threads (chapter 4) Dr. İbrahim Körpeoğlu http://www.cs.bilkent.edu.tr/~korpe 1 References The slides here are adapted/modified

More information

LSN 13 Linux Concurrency Mechanisms

LSN 13 Linux Concurrency Mechanisms LSN 13 Linux Concurrency Mechanisms ECT362 Operating Systems Department of Engineering Technology LSN 13 Creating Processes fork() system call Returns PID of the child process created The new process is

More information

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution

More information

Last class: Today: Thread Background. Thread Systems

Last class: Today: Thread Background. Thread Systems 1 Last class: Thread Background Today: Thread Systems 2 Threading Systems 3 What kind of problems would you solve with threads? Imagine you are building a web server You could allocate a pool of threads,

More information

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

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time. What is concurrency? Concurrency Johan Montelius KTH 2017 Concurrency: (the illusion of) happening at the same time. A property of the programing model. Why would we want to do things concurrently? What

More information

Concurrency. Johan Montelius KTH

Concurrency. Johan Montelius KTH Concurrency Johan Montelius KTH 2017 1 / 32 What is concurrency? 2 / 32 What is concurrency? Concurrency: (the illusion of) happening at the same time. 2 / 32 What is concurrency? Concurrency: (the illusion

More information

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

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή EPL372 Lab Exercise 2: Threads and pthreads Εργαστήριο 2 Πέτρος Παναγή 1 Threads Vs Processes 2 Process A process is created by the operating system, and requires a fair amount of "overhead". Processes

More information

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

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage) 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

More information

Processes, Threads, SMP, and Microkernels

Processes, Threads, SMP, and Microkernels Processes, Threads, SMP, and Microkernels Slides are mainly taken from «Operating Systems: Internals and Design Principles, 6/E William Stallings (Chapter 4). Some materials and figures are obtained from

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 8 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many partners can we cave for project:

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. September 4, 2014 Topics Overview

More information

Operating systems fundamentals - B06

Operating systems fundamentals - B06 Operating systems fundamentals - B06 David Kendall Northumbria University David Kendall (Northumbria University) Operating systems fundamentals - B06 1 / 12 Introduction Introduction to threads Reminder

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Threads & Concurrency 2 Why Use Threads? Utilize multiple CPU s concurrently Low cost communication via shared memory Overlap computation and blocking

More information

THREADS. Jo, Heeseung

THREADS. Jo, Heeseung THREADS Jo, Heeseung TODAY'S TOPICS Why threads? Threading issues 2 PROCESSES Heavy-weight A process includes many things: - An address space (all the code and data pages) - OS resources (e.g., open files)

More information

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

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam 95.300 Operating Systems Threads and Signals Amir Ghavam Winter 2002 1 Traditional Process Child processes created from a parent process using fork Drawbacks Fork is expensive: Memory is copied from a

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2019 Lecture 7 Threads Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Amdahls law example: Person

More information

Processes & Threads. Wang Xiaolin June 18, 2014

Processes & Threads. Wang Xiaolin June 18, 2014 Processes & Threads Wang Xiaolin wx672ster+os@gmail.com June 18, 2014 Todo: Add Linux Process and Thread Contents 1 Processes 2 1.1 What s a Process..................................... 2 1.2 PCB.............................................

More information

CISC2200 Threads Spring 2015

CISC2200 Threads Spring 2015 CISC2200 Threads Spring 2015 Process We learn the concept of process A program in execution A process owns some resources A process executes a program => execution state, PC, We learn that bash creates

More information

Threads. CS3026 Operating Systems Lecture 06

Threads. CS3026 Operating Systems Lecture 06 Threads CS3026 Operating Systems Lecture 06 Multithreading Multithreading is the ability of an operating system to support multiple threads of execution within a single process Processes have at least

More information

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

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 15-213 The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001 Topics Thread concept Posix threads (Pthreads) interface Linux Pthreads implementation Concurrent execution Sharing data

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2013 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

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

CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion: CSEN 602-Operating Systems, Spring 2018 Practice Assignment 2 Solutions Discussion: 10.2.2018-15.2.2018 Exercise 2-1: Reading Read sections 2.1 (except 2.1.7), 2.2.1 till 2.2.5. 1 Exercise 2-2 In Fig.1,

More information

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

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017 CSCI4430 Data Communication and Computer Networks Pthread Programming ZHANG, Mi Jan. 26, 2017 Outline Introduction What is Multi-thread Programming Why to use Multi-thread Programming Basic Pthread Programming

More information

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

Multithreading. Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4 Multithreading Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4 Understanding Linux/Unix Programming, Bruce Molay, Prentice-Hall, 2003. EEL 602 1 Outline Process and Threads Multithreading

More information

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

Outline. CS4254 Computer Network Architecture and Programming. Introduction 2/4. Introduction 1/4. Dr. Ayman A. Abdel-Hamid. Threads Dr. Ayman Abdel-Hamid, CS4254 Spring 2006 1 CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department Virginia Tech Threads Outline Threads (Chapter

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2016 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2018 Lecture 7 Threads Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many processes can a core

More information

4.8 Summary. Practice Exercises

4.8 Summary. Practice Exercises Practice Exercises 191 structures of the parent process. A new task is also created when the clone() system call is made. However, rather than copying all data structures, the new task points to the data

More information

Concurrent Programming. Concurrent Programming with Processes and Threads

Concurrent Programming. Concurrent Programming with Processes and Threads Concurrent Programming Concurrent Programming with Processes and Threads Review The fork system call creates a process Memory and resources are allocated The exec system call allow a program to execute

More information

4. Concurrency via Threads

4. Concurrency via Threads CSC400 - Operating Systems 4. Concurrency via Threads J. Sumey Overview Multithreading Concept Background Implementations Thread States & Thread Switching Thread Operations Case Study: pthreads CSC400

More information

CS 5523 Operating Systems: Thread and Implementation

CS 5523 Operating Systems: Thread and Implementation When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate

More information

CS 261 Fall Mike Lam, Professor. Threads

CS 261 Fall Mike Lam, Professor. Threads CS 261 Fall 2017 Mike Lam, Professor Threads Parallel computing Goal: concurrent or parallel computing Take advantage of multiple hardware units to solve multiple problems simultaneously Motivations: Maintain

More information

Roadmap. Concurrent Programming. Concurrent Programming. Motivation. Why Threads? Tevfik Ko!ar. CSC Systems Programming Fall 2010

Roadmap. Concurrent Programming. Concurrent Programming. Motivation. Why Threads? Tevfik Ko!ar. CSC Systems Programming Fall 2010 CSC 0 - Systems Programming Fall 00 Lecture - XIII Concurrent Programming - I Roadmap Sequential vs Concurrent Programming Shared Memory vs Message Passing Divide and Compute Threads vs Processes POSIX

More information

CS Operating Systems: Threads (SGG 4)

CS Operating Systems: Threads (SGG 4) When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate

More information

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CMPSC 311- Introduction to Systems Programming Module: Concurrency CMPSC 311- Introduction to Systems Programming Module: Concurrency Professor Patrick McDaniel Fall 2013 Sequential Programming Processing a network connection as it arrives and fulfilling the exchange

More information

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

Threads. To do. Why threads? Thread model & implementation. q q q. q Next time: Synchronization Threads To do q q q Why threads? Thread model & implementation q Next time: Synchronization What s in a process A process consists of (at least): An address space Code and data for the running program

More information

POSIX Threads. HUJI Spring 2011

POSIX Threads. HUJI Spring 2011 POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time

More information

CSE 333 SECTION 9. Threads

CSE 333 SECTION 9. Threads CSE 333 SECTION 9 Threads HW4 How s HW4 going? Any Questions? Threads Sequential execution of a program. Contained within a process. Multiple threads can exist within the same process. Every process starts

More information

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

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control Processes & Threads Concurrent Programs Process = Address space + one thread of control Concurrent program = multiple threads of control Multiple single-threaded processes Multi-threaded process 2 1 Concurrent

More information

Definition Multithreading Models Threading Issues Pthreads (Unix)

Definition Multithreading Models Threading Issues Pthreads (Unix) Chapter 4: Threads Definition Multithreading Models Threading Issues Pthreads (Unix) Solaris 2 Threads Windows 2000 Threads Linux Threads Java Threads 1 Thread A Unix process (heavy-weight process HWP)

More information

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

Threads. Today. Next time. Why threads? Thread model & implementation. CPU Scheduling Threads Today Why threads? Thread model & implementation Next time CPU Scheduling What s in a process A process consists of (at least): An address space Code and data for the running program Thread state

More information

ECE 598 Advanced Operating Systems Lecture 23

ECE 598 Advanced Operating Systems Lecture 23 ECE 598 Advanced Operating Systems Lecture 23 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 21 April 2016 Don t forget HW#9 Midterm next Thursday Announcements 1 Process States

More information

Processes and Threads

Processes and Threads TDDI04 Concurrent Programming, Operating Systems, and Real-time Operating Systems Processes and Threads [SGG7] Chapters 3 and 4 Copyright Notice: The lecture notes are mainly based on Silberschatz s, Galvin

More information

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

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 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 independently from its main program. Multi-threaded programs

More information

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

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005 Threads vs. Processes Lecture 4 Thread Programming January 21, 2005 fork() is expensive (time, memory) Interprocess communication is hard. Threads are lightweight processes: one process can contain several

More information

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Slides based on the book Operating System Concepts, 9th Edition, Abraham Silberschatz, Peter B. Galvin and Greg Gagne,

More information

Computer Systems Laboratory Sungkyunkwan University

Computer Systems Laboratory Sungkyunkwan University Threads Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Today s Topics Why threads? Threading issues 2 Processes Heavy-weight A process includes

More information

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

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5 CS 153 Lab4 and 5 Kishore Kumar Pusukuri Outline Introduction A thread is a straightforward concept : a single sequential flow of control. In traditional operating systems, each process has an address

More information

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song CSCE 313 Introduction to Computer Systems Instructor: Dezhen Song Programs, Processes, and Threads Programs and Processes Threads Programs, Processes, and Threads Programs and Processes Threads Processes

More information

CSCE 313: Intro to Computer Systems

CSCE 313: Intro to Computer Systems CSCE 313 Introduction to Computer Systems Instructor: Dr. Guofei Gu http://courses.cse.tamu.edu/guofei/csce313/ Programs, Processes, and Threads Programs and Processes Threads 1 Programs, Processes, and

More information

Introduction to PThreads and Basic Synchronization

Introduction to PThreads and Basic Synchronization Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization

More information

Threaded Programming. Lecture 9: Alternatives to OpenMP

Threaded Programming. Lecture 9: Alternatives to OpenMP Threaded Programming Lecture 9: Alternatives to OpenMP What s wrong with OpenMP? OpenMP is designed for programs where you want a fixed number of threads, and you always want the threads to be consuming

More information

Introduction to pthreads

Introduction to pthreads CS 220: Introduction to Parallel Computing Introduction to pthreads Lecture 25 Threads In computing, a thread is the smallest schedulable unit of execution Your operating system has a scheduler that decides

More information

Thread and Synchronization

Thread and Synchronization Thread and Synchronization pthread Programming (Module 19) Yann-Hang Lee Arizona State University yhlee@asu.edu (480) 727-7507 Summer 2014 Real-time Systems Lab, Computer Science and Engineering, ASU Pthread

More information

Introduction to Multicore Programming

Introduction to Multicore Programming Introduction to Multicore Programming Minsoo Ryu Department of Computer Science and Engineering 2 1 Multithreaded Programming 2 Automatic Parallelization and OpenMP 3 GPGPU 2 Multithreaded Programming

More information

Operating Systems & Concurrency: Process Concepts

Operating Systems & Concurrency: Process Concepts Operating Systems & Concurrency: Process Concepts Michael Brockway October 6, 2011 Outline Processes - context, data area, states Process creation, termination unix examples Processes and threads Processes

More information

Computer Systems Laboratory Sungkyunkwan University

Computer Systems Laboratory Sungkyunkwan University Concurrent Programming Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int main (int argc, char *argv[]) {... listenfd = socket(af_inet, SOCK_STREAM, 0); bzero((char

More information

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

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1 Thread Disclaimer: some slides are adopted from the book authors slides with permission 1 IPC Shared memory Recap share a memory region between processes read or write to the shared memory region fast

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

CS Lecture 3! Threads! George Mason University! Spring 2010!

CS Lecture 3! Threads! George Mason University! Spring 2010! CS 571 - Lecture 3! Threads! George Mason University! Spring 2010! Threads! Overview! Multithreading! Example Applications! User-level Threads! Kernel-level Threads! Hybrid Implementation! Observing Threads!

More information

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

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It

More information

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

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source: Agenda POSIX Threads Programming 1 Process vs Thread process thread Picture source: https://computing.llnl.gov/tutorials/pthreads/ 2 Shared Memory Model Picture source: https://computing.llnl.gov/tutorials/pthreads/

More information

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

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process EECS 3221 Operating System Fundamentals What is thread? Thread Concept No. 3 Thread Difference between a process and a thread Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University

More information

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

Threads. CS-3013 Operating Systems Hugh C. Lauer. CS-3013, C-Term 2012 Threads 1 Threads CS-3013 Operating Systems Hugh C. Lauer (Slides include materials from Slides include materials from Modern Operating Systems, 3 rd ed., by Andrew Tanenbaum and from Operating System Concepts,

More information

PRACE Autumn School Basic Programming Models

PRACE Autumn School Basic Programming Models PRACE Autumn School 2010 Basic Programming Models Basic Programming Models - Outline Introduction Key concepts Architectures Programming models Programming languages Compilers Operating system & libraries

More information

Chapter 4 Concurrent Programming

Chapter 4 Concurrent Programming Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware

More information

CSC209H Lecture 11. Dan Zingaro. March 25, 2015

CSC209H Lecture 11. Dan Zingaro. March 25, 2015 CSC209H Lecture 11 Dan Zingaro March 25, 2015 Level- and Edge-Triggering (Kerrisk 63.1.1) When is an FD ready? Two answers: Level-triggered: when an operation will not block (e.g. read will not block),

More information

Operating Systems. Lab. Class Project #5

Operating Systems. Lab. Class Project #5 Operating Systems Lab. Class Project #5 Project Plan 6 projects 0. Install xv6 1. System call 2. Scheduling 3. Memory 4. Virtual memory 5. Concurrency 1 6. Concurrency 2 Individual projects 2017-05-16

More information

Lecture Topics. Announcements. Today: Threads (Stallings, chapter , 4.6) Next: Concurrency (Stallings, chapter , 5.

Lecture Topics. Announcements. Today: Threads (Stallings, chapter , 4.6) Next: Concurrency (Stallings, chapter , 5. Lecture Topics Today: Threads (Stallings, chapter 4.1-4.3, 4.6) Next: Concurrency (Stallings, chapter 5.1-5.4, 5.7) 1 Announcements Make tutorial Self-Study Exercise #4 Project #2 (due 9/20) Project #3

More information

Threads. lightweight processes

Threads. lightweight processes Threads lightweight processes 1 Motivation Processes are expensive to create. It takes quite a bit of time to switch between processes Communication between processes must be done through an external kernel

More information

Chapter 3 Process Description and Control

Chapter 3 Process Description and Control Operating Systems: Internals and Design Principles Chapter 3 Process Description and Control Seventh Edition By William Stallings Process Control Block Structure of Process Images in Virtual Memory How

More information

ECE 7650 Scalable and Secure Internet Services and Architecture ---- A Systems Perspective. Part I: Operating system overview: Processes and threads

ECE 7650 Scalable and Secure Internet Services and Architecture ---- A Systems Perspective. Part I: Operating system overview: Processes and threads ECE 7650 Scalable and Secure Internet Services and Architecture ---- A Systems Perspective Part I: Operating system overview: Processes and threads 1 Overview Process concept Process scheduling Thread

More information

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 4: MULTITHREADED PROGRAMMING

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 4: MULTITHREADED PROGRAMMING I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 4: MULTITHREADED PROGRAMMING Chapter 4: Multithreaded Programming Overview Multithreading Models Thread Libraries Threading

More information

Lecture Contents. 1. Overview. 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary

Lecture Contents. 1. Overview. 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary Lecture 4 Threads 1 Lecture Contents 1. Overview 2. Multithreading Models 3. Examples of Thread Libraries 4. Summary 2 1. Overview Process is the unit of resource allocation and unit of protection. Thread

More information

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

Section 4: Threads CS162. September 15, Warmup Hello World Vocabulary 2 CS162 September 15, 2016 Contents 1 Warmup 2 1.1 Hello World............................................ 2 2 Vocabulary 2 3 Problems 3 3.1 Join................................................ 3 3.2 Stack

More information

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

Programming with Shared Memory. Nguyễn Quang Hùng Programming with Shared Memory Nguyễn Quang Hùng Outline Introduction Shared memory multiprocessors Constructs for specifying parallelism Creating concurrent processes Threads Sharing data Creating shared

More information

Creating Threads. Programming Details. COMP750 Distributed Systems

Creating Threads. Programming Details. COMP750 Distributed Systems Creating Threads Programming Details COMP750 Distributed Systems Thread and Process Creation Processes can be created on Unix systems in C or C++ using the fork() function. Threads can be created in C

More information

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

Overview. Administrative. * HW 2 Grades. * HW 3 Due. Topics: * What are Threads? * Motivating Example : Async. Read() * POSIX Threads Overview Administrative * HW 2 Grades * HW 3 Due Topics: * What are Threads? * Motivating Example : Async. Read() * POSIX Threads * Basic Thread Management * User vs. Kernel Threads * Thread Attributes

More information

מצליחה. 1. int fork-bomb() 2. { 3. fork(); 4. fork() && fork() fork(); 5. fork(); printf("bla\n"); 8. return 0; 9. }

מצליחה. 1. int fork-bomb() 2. { 3. fork(); 4. fork() && fork() fork(); 5. fork(); printf(bla\n); 8. return 0; 9. } שאלה : (4 נקודות) א. ב. ג. (5 נקודות) הגדירו את המונח race-condition במדוייק לא להשמיט פרטים. ספקו דוגמא. (5 נקודות) מהו? Monitor נא לספק הגדרה מלאה. ( נקודות) ( נקודות) ציינו כמה תהליכים יווצרו בקוד הבא

More information

POSIX Threads. Paolo Burgio

POSIX Threads. Paolo Burgio POSIX Threads Paolo Burgio paolo.burgio@unimore.it The POSIX IEEE standard Specifies an operating system interface similar to most UNIX systems It extends the C language with primitives that allows the

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2019 Lecture 6 Processes Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Fork( ) causes a branch

More information

CS533 Concepts of Operating Systems. Jonathan Walpole

CS533 Concepts of Operating Systems. Jonathan Walpole CS533 Concepts of Operating Systems Jonathan Walpole Introduction to Threads and Concurrency Why is Concurrency Important? Why study threads and concurrent programming in an OS class? What is a thread?

More information

Concurrent Server Design Multiple- vs. Single-Thread

Concurrent Server Design Multiple- vs. Single-Thread Concurrent Server Design Multiple- vs. Single-Thread Chuan-Ming Liu Computer Science and Information Engineering National Taipei University of Technology Fall 2007, TAIWAN NTUT, TAIWAN 1 Examples Using

More information

CS444 1/28/05. Lab 03

CS444 1/28/05. Lab 03 CS444 1/28/05 Lab 03 Note All the code that is found in this lab guide can be found at the following web address: www.clarkson.edu/class/cs444/cs444.sp2005/labs/lab03/code/ Threading A thread is an independent

More information

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

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017 Preview What are Pthreads? What is Pthreads The Thread ID The Thread Creation The thread Termination The pthread_join() function Mutex The pthread_cancel function The pthread_cleanup_push() function The

More information