Lecture 9: POSIX Threads Cont.

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

1 Threads. 2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment.
Professor: Shu-Ching Chen TA: Hsin-Yu Ha.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int c;
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
B.Ramamurthy1 POSIX Thread Programming 2/14/97 B.Ramamurthy.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
PRINCIPLES OF OPERATING SYSTEMS Lecture 6: Processes CPSC 457, Spring 2015 May 21, 2015 M. Reza Zakerinasab Department of Computer Science, University.
The University of Adelaide, School of Computer Science
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
CS333 Intro to Operating Systems Jonathan Walpole.
Professor: Shu-Ching Chen TA: Samira Pouyanfar.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int.
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Pthreads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Windows Threading Colin Roby Jaewook Kim.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
2.2 Threads  Process: address space + code execution  There is no law that states that a process cannot have more than one “line” of execution.  Threads:
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Realizing Concurrency using the thread model
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Lesson One – Creating a thread
Realizing Concurrency using the thread model
Auburn University COMP7330/7336 Advanced Parallel and Distributed Computing Thread Basics Dr. Xiao Qin Auburn University.
Threads in C Caryl Rahn.
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
CS399 New Beginnings Jonathan Walpole.
Thread Programming.
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Principles of Operating Systems Lecture 8
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
CSE 333 – Section 9 Threads.
Realizing Concurrency using the thread model
Lecture 8: POSIX Threads
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Thread Programming.
Realizing Concurrency using the thread model
CS510 Operating System Foundations
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Lecture 8: POSIX Threads
Tutorial 4.
Shared Memory Programming with Pthreads
POSIX Threads(pthreads)
Presentation transcript:

Lecture 9: POSIX Threads Cont.

Review: pthread_create() Use pthread_create() to add a new thread of control to the current process. int pthread_create( pthread_t *tid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg);

Review: pthread_create() Use pthread_create() to add a new thread of control to the current process. int pthread_create( pthread_t *tid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg); The function writes the thread id in tid.

Review: pthread_create() Use pthread_create() to add a new thread of control to the current process. int pthread_create( pthread_t *tid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg); The address of a thread attribute object is passed using tattr.

Review: pthread_create() Use pthread_create() to add a new thread of control to the current process. int pthread_create( pthread_t *tid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg); The thread runs a function passed in start_routine.

Review: pthread_create() Use pthread_create() to add a new thread of control to the current process. int pthread_create( pthread_t *tid, const pthread_attr_t *tattr, void*(*start_routine)(void *), void *arg); The start routine’s arguments are passed with arg.

Review: The thread attribute object The attributes of a thread are held in a thread attribute object, which is a struct defined in pthread.h. You can declare a pthread attribute in your code, but it can only be initialized or modified by the following functions: int pthread_attr_init(pthread_attr_t *attr); pthread_attr_setstackaddr(); pthread_attr_setstacksize(); pthread_attr_setdetachstate();

In this lecture pthread_exit() pthread_join() pthread_yield()

Thread termination An important special case arises when the initial thread — the one calling main() — returns from main() or calls exit(). This action causes the entire process to terminate, along with all its threads. So take care to ensure that the initial thread does not return from main() prematurely. Note that when the main thread merely calls pthread_exit(), it terminates only itself—the other threads in the process, as well as the process, continue to exist. The process terminates when all its threads terminate.

pthread_join() Use pthread_join() to wait for a thread to terminate. Prototype: int pthread_join( thread_t tid, void **status); The pthread_join() function blocks the calling thread until the thread specified by tid terminates. The specified thread must be in the current process and non-detached

An example func(int r_in, int r_out, int l_in, int l_out) { } pthread_t in_thread, out_thread; two_ints_t in={r_in, l_out}, out={l_in, r_out}; pthread_create(&in_thread, 0, incoming, &in); pthread_create(&out_thread, 0, outgoing, &out); pthread_join(in_thread, 0); pthread_join(out_thread, 0); //do some other work … return; } However, if we can guarantee that the mainline thread does not return from rlogind until after the new threads have terminated, then our means for passing multiple arguments is safe. In the example above, the mainline thread places calls to pthread_join, which does not return until the thread mentioned as its first argument has terminated. Thus the mainline thread waits until the new threads terminate and then returns from rlogind. Copyright © 2002 Thomas W. Doeppner. All rights reserved.

Waiting for threads The exit status of the thread specified by tid is written to status when pthread_join() returns successfully. Multiple threads cannot wait for the same thread to terminate. If they try to, one thread returns successfully and the others fail with an error of ESRCH.

pthread_yield() One thread can yield CPU to other threads Prototype int pthread_yield(void);

Detached Threads start_servers( ) { server( ) { pthread_t thread; int i; for (i=0; i<nr_of_server_threads; i++) { pthread_create(&thread, 0, server, 0); pthread_detach(thread); } ... server( ) { If there is no reason to synchronize with the termination of a thread, then it is rather a nuisance to have to call pthread_join. Instead, one can arrange for a thread to be detached. Such threads “vanish” when they terminate—not only do they not need to be joined with, but they cannot be joined with. Copyright © 2002 Thomas W. Doeppner. All rights reserved.

Example: matrix multiplication #include <stdio.h> #include <pthread.h> #include <string.h> #define M 3 #define N 4 #define P 5 int A[M][N]; int B[N][P]; int C[M][P]; void *matmult(void *); main( ) { int i; pthread_t thr[M]; int error; /* initialize the matrices ... */ ... In this series of slides we present a simple example of an (almost) complete program—one that multiplies two matrices using a number of threads. Our algorithm is not an example of an efficient matrix-multiplication algorithm, but it shows us everything that must be included to make a multithreaded C program compile and run. Our approach is to use the most straightforward technique for multiplying two matrices: each element of the product is formed by directly taking the inner product of a row of the multiplier and a column of the multiplicand. We employ multiple threads by assigning a thread to compute each row of the product. This slide shows the necessary includes, global declarations, and the beginning of the main routine. Copyright © 2002 Thomas W. Doeppner. All rights reserved.

Example Cont. for (i=0; i<M; i++) { // create the worker threads if (error = pthread_create( &thr[i], NULL, matmult, (void *)i)) { fprintf(stderr, "pthread_create: %s", strerror(error)); exit(1); } for (i=0; i<M; i++) // wait for workers to finish their jobs pthread_join(thr[i], 0) /* print the results ... */ Here we have the remainder of main. It creates a number of threads, one for each row of the result matrix, waits for all of them to terminate, then prints the results (this last step is not spelled out). Note that we check for errors when calling pthread_create. (It is important to check for errors after calls to almost all of the pthread routines, but we normally omit it in the slides for lack of space.) For reasons discussed later, the pthread calls, unlike Unix system calls, do not return -1 if there is an error, but return the error code itself (and return zero on success). However, one can find the text associated with error codes, just as for Unix-system-call error codes, by calling strerror. So that the first thread is certain that all the other threads have terminated, it must call pthread_join on each of them. Copyright © 2002 Thomas W. Doeppner. All rights reserved.

Example Cont. void *matmult(void *arg) { int row = (int)arg; int col; Int j; int t; for (col=0; col < P; col++) { t = 0; for (j=0; j<N; j++) t += A[row][j] * B[j][col]; C[row][col] = t; } return(0); Here is the code executed by each of the threads. It’s pretty straightforward: it merely computes a row of the result matrix. Note how the argument is explicitly converted from void * to int. Copyright © 2002 Thomas W. Doeppner. All rights reserved.