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

Size: px
Start display at page:

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

Transcription

1 CPSC 341 OS & Networks Threads Dr. Yingwu Zhu

2 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 information Execution state (PC, SP, regs, etc.) Creating a new process is costly because of all of the data structures that must be allocated and initialized FreeBSD: 81 fields, 408 bytes which does not even include page tables, etc. Communicating between processes is costly because most communication goes through the OS Overhead of system calls and copying data

3 Parallel Programs Recall the Web server example that forks off copies of itself to handle multiple simultaneous requests Or any parallel program that executes on a multiprocessor To execute these programs we need to Create several processes that execute in parallel Cause each to map to the same address space to share data They are all part of the same computation Have the OS schedule these processes in parallel (logically or physically) This situation is very inefficient Space: PCB, page tables, etc. Time: create data structures, fork and copy addr space, etc.

4 Rethinking Processes What is similar in these cooperating processes? They all share the same code and data (address space) They all share the same privileges They all share the same resources (files, sockets, etc.) What don t they share? Each has its own execution state: PC, SP, and registers Key idea: Why don t we separate the concept of a process from its execution state? Process: address space, privileges, resources, etc. Execution state: PC, SP, registers Exec state also called thread of control, or thread

5 Threaded Applications Web browsers: display and data retrieval Web servers Many others

6 Threads Modern OSes (Mach, Chorus, NT, modern Unix) separate the concepts of processes and threads The thread defines a sequential execution stream within a process (PC, SP, registers) The process defines the address space and general process attributes (everything but threads of execution) A thread is bound to a single process Processes, however, can have multiple threads Threads become the unit of scheduling Processes are now the containers in which threads execute Processes become static, threads are the dynamic entities

7 Threads Basic unit of CPU utilization Each thread contains its own (my privacy!) Thread ID PC Register set Stack All threads in a process share (do not pollute the public area!) Text section (program) Heap Data section (global variables) File descriptors

8 Threads in a Process

9 Process/Thread Separation Separating threads and processes makes it easier to support multithreaded applications Creating concurrency does not require creating new processes Concurrency (multithreading) can be very useful Improving program structure Handling concurrent events (e.g., Web requests) Writing parallel programs So multithreading is even useful on a uniprocessor

10 Why Multithreading? Creating processes are expensive! Responsiveness Web browsers: one thread for interactivity while others are retrieving images Resource Sharing share memory and resources of the process they belong to Sharing code and data allow different threads of activity within the same address space Economy Processes are expensive to create, and do context-switch In Solaris Process creating is about 30 times slower Context-switch is about 5 times slower Utilization of MP Architectures A single-threaded process can only run on one CPU

11 Threads: Concurrent Servers

12 Threads: Concurrent Servers

13 Thread Type User threads Kernel threads Three primary thread libraries: POSIX Pthreads (user & kernel): our case study Win32 threads (kernel-level) Java threads (depending on OS)

14 Kernel Threads Supported by the Kernel OS-managed threads are called kernel-level threads or lightweight processes NT: threads Solaris: lightweight processes (LWP) Advantages Non-blocking thread execution (Similar to processes, when a kernel thread makes a blocking call, only that thread blocks ) Multi-processors (threads on different processors) No need to worry about starving other threads, preemptive scheduling

15 Kernel Thread Limitations Kernel-level threads make concurrency much cheaper than processes Much less state to allocate and initialize However, for fine-grained concurrency, kernel-level threads still suffer from too much overhead Thread operations still require system calls Ideally, want thread operations to be as fast as a procedure call Kernel-level threads have to be general to support the needs of all programmers, languages, runtimes, etc. For such fine-grained concurrency, need even cheaper threads

16 User Thread To make threads cheap and fast, they need to be implemented at user level Kernel-level threads are managed by the OS User-level threads are managed entirely by the run-time system (user-level library) User-level threads are small and fast A thread is simply represented by a PC, registers, stack, and small thread control block (TCB) Creating a new thread, switching between threads, and synchronizing threads are done via procedure call No kernel involvement; No kernel resources allocated to the threads User-level thread operations 100x faster than kernel threads

17 User Thread Limitations But, user-level threads are not a perfect solution As with everything else, they are a tradeoff User-level threads are invisible to the OS They are not well integrated with the OS As a result, the OS can make poor decisions Scheduling a process with idle threads Blocking a process whose thread initiated an I/O, even though the process has other threads that can execute Unscheduling a process with a thread holding a lock A single thread can monopolize the timeslice thus starving the other threads within the same process Solving this requires communication between the kernel and the user-level thread manager

18 Kernel vs. User Threads Kernel-level threads Integrated with OS (informed scheduling) Slow to create, manipulate, synchronize User-level threads Fast to create, manipulate, synchronize Not integrated with OS (uninformed scheduling) Understanding the differences between kernel and user-level threads is important For programming (correctness, performance) For test-taking

19 Kernel vs. User Threads Another possibility is to use both kernel and user-level threads Can associate a user-level thread with a kernel-level thread Or, multiplex user-level threads on top of kernel-level threads Java Virtual Machine (JVM) Java threads are user-level threads On older Unix, only one kernel thread per process Multiplex all Java threads on this one kernel thread On NT, Solaris, OSF Can multiplex Java threads on multiple kernel threads Can have more Java threads than kernel threads Why?

20 Kernel vs. User Threads

21 Case Study: Pthread How to Compile Creating and destroying threads How to use POSIX threads

22 Reading Materials Reading posted suppl. material on threads 4.1 in the chapter

23 How to compile? $ gcc Wall o proj proj.c pthread or $ g++ Wall o proj proj.cpp pthread The option specifies that pthreads library should be linked (libpthread: pthread APIs) causes the complier to properly handle multiple threads in the code that it generates Other platform/compiler may user other options, eg., -lpthread #include <pthread.h> All thread functions and data types are declared in the header file

24 Creating Threads int pthread_create (pthread_t *thread_id, pthread_attr_t *attr, void *(*thread_fun)(void *), void *args); - The #1 para returns thread ID (a unique ID per thread) The #2 para pointing to thread attr. NULL represents using the default attr. settings; controls details of how the thread interacts with the rest of the program - The #3 para as pointer to a function the thread is to execute, of the type: void* (*) (void*) The function receives an argument in #4 and return data from the thread to the creator; entry point of the created thread s execution! - The #4 para is the arguments to the function - Return 0 on success; failure otherwise

25 Creating Threads pthread_create() A call to pthread_create returns immediately, and the original thread continues executing the instructions following the call Meanwhile, the new thread begins executing the thread function. Simply put, they run concurrently competing for CPU cycles. Hard to predict the execution order (that is why we study Synchronization later)

26 Creating Threads #include <pthread.h> #include <stdio.h> void * entry_point(void *arg) { printf("hello world!\n"); return NULL; } int main(int argc, char **argv) { pthread_t thr; if(pthread_create(&thr, NULL, &entry_point, NULL)) { printf("could not create thread\n"); return -1; } if(pthread_join(thr, NULL)) { printf("could not join thread\n"); return -1; } return 0; }

27 Thread Terminates & Return Value Pthreads terminate when the function returns, or the thread calls pthread_exit() int pthread_exit(void *status); status is the return value of the thread A thread_fun returns a void*, so calling return (void *) is the equivalent of this function the pthread_exit() routine does not close files; any files opened inside the thread will remain open after the thread is terminated

28 Example #include <pthread.h> #include <stdio.h> void * entry_point(void *arg) { printf("hello world!\n"); pthread_exit(null); //return NULL; } int main(int argc, char **argv) { pthread_t thr; if(pthread_create(&thr, NULL, &entry_point, NULL)) { printf("could not create thread\n"); return -1; } if(pthread_join(thr, NULL)) { printf("could not join thread\n"); return -1; } return 0; }

29 Joining Threads int pthread_join(pthread_t thread_id, void **status) #1 para: the thread ID of the thread to wait for #2 para: receive the finished thread s return value One thread can wait (or block) on the termination of another by using pthread_join() You can collect the exit status of all threads you created by pthread_join(), via status Similar to system call wait() in processes

30 Example #include <pthread.h> #include <stdio.h> void * entry_point(void *arg) { printf("hello world!\n"); pthread_exit(null); //return NULL; } int main(int argc, char **argv) { pthread_t thr; if(pthread_create(&thr, NULL, &entry_point, NULL)) { printf("could not create thread\n"); return -1; } if(pthread_join(thr, NULL)) { printf("could not join thread\n"); return -1; } return 0; }

31 Kill Threads Kill a thread before it returns normally using pthread_cancel() But Make sure the thread has released any local resources; unlike processes, the OS will not clean up the resources Why? Threads in a process share resources

32 #include <pthread.h> #include <stdio.h> /* Parameters to print_function. */ struct char_print_parms { }; /* The character to print. */ Passing Data to Threads char character; /* The number of times to print it. */ int count; /* Prints a number of characters to stderr, as given by PARAMETERS, which is a pointer to a struct char_print_parms. */ void* char_print (void* parameters) { } /* Cast the cookie pointer to the right type. */ struct char_print_parms* p = (struct char_print_parms*) parameters; int i; for (i = 0; i < p->count; ++i) fputc (p->character, stderr); return NULL;

33 Passing Data to Threads int main () { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; } /* Create a new thread to print 30,000 x s. */ thread1_args.character = x ; thread1_args.count = 30000; pthread_create (&thread1_id, NULL, &char_print, (void*)&thread1_args); /* Create a new thread to print 20,000 o s. */ thread1_args.character = o ; thread1_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, (void*)&thread1_args); return 0;

34 Passing Data to Threads One argument as void* Common practice Pass a pointer to some structure or array of data The above program example has a problem thread1_args Solution?

35 Passing Data to Threads int main () { pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args; /* Create a new thread to print 30,000 x s. */ thread1_args.character = x ; thread1_args.count = 30000; pthread_create (&thread1_id, NULL, &char_print, (void*)&thread1_args); /* Create a new thread to print 20,000 o s. */ thread2_args.character = o ; thread2_args.count = 20000; pthread_create (&thread2_id, NULL, &char_print, (void*)&thread2_args); return 0; }

36 Problems/Bugs? Wait! We have one more BUG!

37 Passing Data to Threads One argument as void* Can not use local structure!!!! Why? (what if the main thread exits first!) Common practice Pass a pointer to some structure or array of data

38 Example on Passing Data struct thread_data{ int thread_id; int sum; char *message; }; struct thread_data thread_data_array[num_threads]; //global void *PrintHello(void *threadarg) { struct thread_data *my_data;... my_data = (struct thread_data *) threadarg; taskid = my_data->thread_id; sum = my_data->sum; hello_msg = my_data->message;... } int main (int argc, char *argv[]) {... thread_data_array[t].thread_id = t; thread_data_array[t].sum = sum; thread_data_array[t].message = messages[t]; rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &thread_data_array[t]);... }

39 Returning Results from Threads Thread function returns a pointer to void: void * Pitfalls in return value

40 Pitfall #1 void *thread_function ( void *) { int code = DEFAULT_VALUE; return ( void *) code ; } Only work in machines where integers can convert to a point and then back to an integer without loss of information

41 Pitfall #2 void *thread_function ( void *) { char buffer[64]; // fill up the buffer with sth good return ( void *) buffer; } This buffer will disappear as the thread function returns

42 Pitfall #3 void *thread_function ( void *) { static char buffer[64]; // fill up the buffer with sth good return ( void *) buffer; } It does not work in the common case of multiple threads running the same thread funciton

43 Right Way void *thread_function ( void *) { char* buffer = (char *)malloc(64); // fill up the buffer with sth good return ( void *) buffer; }

44 Right Way int main() { void *exit_state; char *buffer;. pthread_join(tid, &exit_state); buffer = (char *) exit_state; printf( from thread %d: %s\n, tid, buffer); free(exit_state); }

45 Exercise Write a multithreaded program that calculates the summation of a non-negative integer in a separate thread ( N) The non-negative integer is from command-line parameter

46 Exercise Write a multithreaded program that calculates the summation of a non-negative integer in a separate thread ( N) The non-negative integer is from command-line parameter Option 1: The summation result is kept in a global variable: int sum; // shared by threads Option 2: The summation result is returned.

47 Step 1: write a thread function void *thread_sum(void *arg) { int i; int m = (int)(*arg); sum = 0; //initialization for (i = 0; i <= m; i++) sum += i; pthread_exit(0); }

48 Step 2: write the main() int sum; int main(int argc, char *argv[]) { pthread_t tid; if (argc!= 2) { printf( Usage: %s <integer-para>\n, argv*0+); return -1; } int i = atoi(argv[1]); if (i < 0) { printf( integer para must be non-negative\n ); return -2; } pthread_create(&tid, NULL, thread_sum, &i); //need to check return value pthread_join(tid, NULL); //need to check return value printf( sum = %d\n, sum); }

49 Exercise Write a program that creates 10 threads. Have each thread execute the same function and pass each thread a unique number. Each thread should print Hello, World (thread n) five times where n is replaced by the thread s given number. Be sure the program doesn t terminate until all the threads are complete. (Try running your program on more than one machine. Are there any differences in how it behaves?)

50 Exercise Which of the following components of program state are shared across threads in a multithreaded process? a. register values b. heap memory c. Global variables d. stack memory

51 What is output? #include <pthread.h> #include <stdio.h> int value = 0; void* runner(void* param); int main(int argc, char* argv[]) { int pid; pthread_t tid; pid = fork(); if (!pid) { pthread_create(&tid, NULL, runner, NULL); pthread_join(tid, NULL); printf( CHILD: value= %d\n, value); } else if (pid>0) { wait(null); printf( PARENT: value = %d\n, value); } } void* runner (void* param) { value = 5; phread_exit(0); }

CSE 120 Principles of Operating Systems

CSE 120 Principles of Operating Systems CSE 120 Principles of Operating Systems Fall 2000 Lecture 5: Threads Geoffrey M. Voelker Processes Recall that a process includes many things An address space (defining all the code and data pages) OS

More information

CSE 120 Principles of Operating Systems

CSE 120 Principles of Operating Systems CSE 120 Principles of Operating Systems Spring 2009 Lecture 4: Threads Geoffrey M. Voelker Announcements Homework #1 due now Project 0 due tonight Project 1 out April 9, 2009 CSE 120 Lecture 4 Threads

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

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

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

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

CSE 120 Principles of Operating Systems

CSE 120 Principles of Operating Systems CSE 120 Principles of Operating Systems Fall 2015 Lecture 4: Threads Geoffrey M. Voelker Announcements Project 0 due Project 1 out October 6, 2015 CSE 120 Lecture 4 Threads 2 Processes Recall that a process

More information

CSE 153 Design of Operating Systems Fall 2018

CSE 153 Design of Operating Systems Fall 2018 CSE 153 Design of Operating Systems Fall 2018 Lecture 4: Processes (2) Threads Process Creation: Unix In Unix, processes are created using fork() int fork() fork() Creates and initializes a new PCB Creates

More information

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

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology Unix Threads & Concurrency Erick Fredj Computer Science The Jerusalem College of Technology 1 Threads Processes have the following components: an address space a collection of operating system state a

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

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

Lecture 4: Threads; weaving control flow

Lecture 4: Threads; weaving control flow Lecture 4: Threads; weaving control flow CSE 120: Principles of Operating Systems Alex C. Snoeren HW 1 Due NOW Announcements Homework #1 due now Project 0 due tonight Project groups Please send project

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

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

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

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

POLITECNICO DI TORINO III Facoltà di Ingegneria dell Informazione INDUSTRIAL NETWORKS AND REAL-TIME OPERATING SYSTEMS. POLITECNICO DI TORINO III Facoltà di Ingegneria dell Informazione INDUSTRIAL NETWORKS AND REAL-TIME OPERATING SYSTEMS LAB 3 All Team No delivery in the laboratory. Do the exercises at home and deliver

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

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

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. 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

CS240: Programming in C. Lecture 18: PThreads

CS240: Programming in C. Lecture 18: PThreads CS240: Programming in C Lecture 18: PThreads Thread Creation Initially, your main() program comprises a single, default thread. pthread_create creates a new thread and makes it executable. This routine

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

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

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

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

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

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

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

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

Chapter 4: Threads. Operating System Concepts with Java 8 th Edition Chapter 4: Threads 14.1 Silberschatz, Galvin and Gagne 2009 Chapter 4: Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples 14.2 Silberschatz, Galvin and Gagne

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

About me Now that you know the pthread API

About me Now that you know the pthread API pthread Examples About me Now that you know the pthread API How do you create threads? How do you pass different values to them? How do you return values from threads? What are some common mistakes? Friday:

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

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

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

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 153 Design of Operating Systems Winter 2016

CS 153 Design of Operating Systems Winter 2016 CS 153 Design of Operating Systems Winter 2016 Lecture 6: Threads Recap: Process Components Per- Process State Per- Thread State A process is named using its process ID (PID) A process contains all of

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

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

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

CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems CS 318 Principles of Operating Systems Fall 2017 Lecture 5: Thread Ryan Huang Administrivia HW1 solution released on Piazza resources Lab 0 grading - In progress - Cheating policy Lab 1 review session

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

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

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

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

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

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

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

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

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

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

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

Threads. Raju Pandey Department of Computer Sciences University of California, Davis Spring 2011

Threads. Raju Pandey Department of Computer Sciences University of California, Davis Spring 2011 Threads Raju Pandey Department of Computer Sciences University of California, Davis Spring 2011 Threads Effectiveness of parallel computing depends on the performance of the primitives used to express

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

Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation. What s in a process? Organizing a Process

Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation. What s in a process? Organizing a Process Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation Why are threads useful? How does one use POSIX pthreads? Michael Swift 1 2 What s in a process? Organizing a Process A process

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

Threads. Computer Systems. 5/12/2009 cse threads Perkins, DW Johnson and University of Washington 1

Threads. Computer Systems.   5/12/2009 cse threads Perkins, DW Johnson and University of Washington 1 Threads CSE 410, Spring 2009 Computer Systems http://www.cs.washington.edu/410 5/12/2009 cse410-20-threads 2006-09 Perkins, DW Johnson and University of Washington 1 Reading and References Reading» Read

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

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

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

CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems CS 318 Principles of Operating Systems Fall 2018 Lecture 5: Thread Ryan Huang Slides adapted from Geoff Voelker s and David Mazières lectures Administrivia Lab 0 grading in progress Lab 1 review session

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

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

Threads (light weight processes) Chester Rebeiro IIT Madras

Threads (light weight processes) Chester Rebeiro IIT Madras Threads (light weight processes) Chester Rebeiro IIT Madras 1 Processes Separate streams of execution Each process isolated from the other Process state contains Process ID Environment Working directory.

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

Notes. CS 537 Lecture 5 Threads and Cooperation. Questions answered in this lecture: What s in a process?

Notes. CS 537 Lecture 5 Threads and Cooperation. Questions answered in this lecture: What s in a process? Notes CS 537 Lecture 5 Threads and Cooperation Michael Swift OS news MS lost antitrust in EU: harder to integrate features Quiz tomorrow on material from chapters 2 and 3 in the book Hardware support for

More information

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

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1 Chapter 4 Threads Images from Silberschatz Pacific University 1 Threads Multiple lines of control inside one process What is shared? How many PCBs? Pacific University 2 Typical Usages Word Processor Web

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

Processes. 4: Threads. Problem needs > 1 independent sequential process? Example: Web Server. Last Modified: 9/17/2002 2:27:59 PM

Processes. 4: Threads. Problem needs > 1 independent sequential process? Example: Web Server. Last Modified: 9/17/2002 2:27:59 PM Processes 4: Threads Last Modified: 9/17/2002 2:27:59 PM Recall: A process includes Address space (Code, Data, Heap, Stack) Register values (including the PC) Resources allocated to the process Memory,

More information

CS 326: Operating Systems. Process Execution. Lecture 5

CS 326: Operating Systems. Process Execution. Lecture 5 CS 326: Operating Systems Process Execution Lecture 5 Today s Schedule Process Creation Threads Limited Direct Execution Basic Scheduling 2/5/18 CS 326: Operating Systems 2 Today s Schedule Process Creation

More information

Concurrent Programming

Concurrent Programming Concurrent Programming CS 485G-006: Systems Programming Lectures 32 33: 18 20 Apr 2016 1 Concurrent Programming is Hard! The human mind tends to be sequential The notion of time is often misleading Thinking

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

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

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

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

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

Threads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr. 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

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

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

Last Class: CPU Scheduling. Pre-emptive versus non-preemptive schedulers Goals for Scheduling: CS377: Operating Systems.

Last Class: CPU Scheduling. Pre-emptive versus non-preemptive schedulers Goals for Scheduling: CS377: Operating Systems. Last Class: CPU Scheduling Pre-emptive versus non-preemptive schedulers Goals for Scheduling: Minimize average response time Maximize throughput Share CPU equally Other goals? Scheduling Algorithms: Selecting

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

Multicore and Multiprocessor Systems: Part I

Multicore and Multiprocessor Systems: Part I Chapter 3 Multicore and Multiprocessor Systems: Part I Max Planck Institute Magdeburg Jens Saak, Scientific Computing II 44/337 Symmetric Multiprocessing Definition (Symmetric Multiprocessing (SMP)) The

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

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

Thread. Operating Systems (Fall/Winter 2018) Yajin Zhou ( Zhejiang University

Thread. Operating Systems (Fall/Winter 2018) Yajin Zhou (  Zhejiang University Operating Systems (Fall/Winter 2018) Thread Yajin Zhou (http://yajin.org) Zhejiang University Acknowledgement: some pages are based on the slides from Zhi Wang(fsu). Review Process Multiple parts: text,

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

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

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

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -

More information

Thread Fundamentals. CSCI 315 Operating Systems Design 1

Thread Fundamentals. CSCI 315 Operating Systems Design 1 Thread Fundamentals Notice: This set of slides is based on the notes by Professor Perrone of Bucknell and the textbook authors Silberschatz, Galvin, and Gagne, as well as the tutorial by Blaise Barney

More information

Parallel Programming with Threads

Parallel Programming with Threads Thread Programming with Shared Memory Parallel Programming with Threads Program is a collection of threads of control. Can be created dynamically, mid-execution, in some languages Each thread has a set

More information

Threads. Jo, Heeseung

Threads. Jo, Heeseung Threads Jo, Heeseung Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2 Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU

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

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

Concurrent Programming

Concurrent Programming Concurrent Programming Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Jinhong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Echo Server Revisited int

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

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

CS Advanced Operating Systems Structures and Implementation Lecture 5. Processes. Goals for Today

CS Advanced Operating Systems Structures and Implementation Lecture 5. Processes. Goals for Today Goals for Today CS194-24 Advanced Operating Systems Structures and Implementation Lecture 5 Processes February 11 th, 2013 Prof. John Kubiatowicz http://inst.eecs.berkeley.edu/~cs194-24 Processes Fork/Exec

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

From Processes to Threads

From Processes to Threads From Processes to Threads 1 Processes, Threads and Processors Hardware can interpret N instruction streams at once Uniprocessor, N==1 Dual-core, N==2 Sun s Niagra T2 (2007) N == 64, but 8 groups of 8 An

More information

CSMC 412. Operating Systems Prof. Ashok K Agrawala Ashok Agrawala Set 4. September 2006 CMSC 412 Set 4

CSMC 412. Operating Systems Prof. Ashok K Agrawala Ashok Agrawala Set 4. September 2006 CMSC 412 Set 4 CSMC 412 Operating Systems Prof. Ashok K Agrawala 2005 Ashok Agrawala Set 4 1 Threads Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads Java Threads 2 Single and

More information