Docsity

Understanding Thread Synchronization with PThreads: Sharing Data Efficiently - Prof. Prasa, Study notes of Operating Systems

Partial preview of the text

Download Understanding Thread Synchronization with PThreads: Sharing Data Efficiently - Prof. Prasa and more Study notes Operating Systems in PDF only on Docsity!

Introduction to PThreads and Basic

Synchronization

Michael Jantz

Dr. Prasad Kulkarni

Introduction

●

In this lab, we will learn about some basic

synchronization issues using PThreads.

●

Grab the tar file for this lab:

  • (^) http://people.eecs.ku.edu/~mjantz/678labs/lab06/lab06.tar ●

Untar it and make the starter code:

  • (^) tar xvzf lab06.tar
  • (^) cd lab06/; make ●

Helpful man pages:

● pthreads(7), pthread_create, pthread_join,

pthread_mutex_init, pthread_mutex_lock

Threads vs. Processes

● When you create a new process, an entire copy of the parent

process' process control block is copied to the child.

● When you create a new thread, only the components of the

process control block that are necessary to create a new

thread of control are actually allocated for the child.

  • (^) A new PC, registers, stack, and some other misc. info are allocated for the new thread.
  • (^) The code and data regions of the PCB are not copied, but are now shared between the parent and the child.

● For these reasons, threads are often thought of as lightweight

processes.

Thread Pros and Cons

● By allowing threads of control to share a common address

space, the thread model provides an efficient way to multi-

task a job over several threads of control.

  • (^) State information for each thread is updated automatically without the use of IPC mechanisms.
  • (^) Context switching from thread to thread is much more efficient than switching the context of an entire process.

● These advantages, however, come with their own drawbacks:

  • (^) The use of shared data must be synchronized between threads.
  • (^) Functions used by multiple threads of control must be reentrant. A reentrant function must not hold static data over successive calls or return a pointer to static data.

Thread Libraries

● For many reasons, thread standards are often implemented

and distributed as libraries.

  • (^) A common standard allows for portable software.
  • (^) Libraries are an efficient way of distributing widely used user level code.
  • (^) Depending on which metrics the programmer cares about, different user level designs of the thread system will yield much different performance. ●

In today's lab, we will the Native POSIX Threads Library,

which implements the POSIX standard for Linux.

The POSIX Standard

● The POSIX standard specifies a set of interfaces (i.e. functions and
header files) that can be used for threaded programming.
● These interfaces require that the underlying implementations meet
a certain set of criteria:
  • (^) Most basically, the underlying implementation must implement threading as described above. Specifically: ● (^) A single process may contain multiple threads, all of which execute the same program. ● (^) Threads share the same global memory (data and heap segments). ● (^) Each thread has its own stack (automatic variables).
  • (^) There are several other characteristics specified by the standard. ● (^) e.g. Threads must share a common process ID, but also have a unique thread ID. ● (^) See the pthreads man page for a complete description of the standard.

ptcount.c

●

Open ptcount.c and read through it to get a feel for

the program's structure. As it is now, the program

doesn't do much.

● The goal of this lab is to learn how PThreads work

by modifying this program to create some number of

threads executing the same routine.

●

The routine each thread executes will spin in two

loops (bound by the OUTER_LOOP_MAX and

INNER_LOOP_MAX command line arguments),

incrementing some global integer for each iteration

of the inner loop.

pthread_create

● (^) The first step is to actually create each pthread using the library routine pthread_create: int pthread_create(pthread_t *restrict thread, const pthread_attr_t restrict attr, void (start_routine)(void), void *restrict arg); ● (^) The arguments are as follows:

  • (^) On return, thread is an address pointing to the allocated thread object.
  • (^) attr,is a pointer to the attribute object for this thread. Attribute objects provide a mechanism for changing the configurable aspects of a thread.
  • (^) start_routine is a pointer to the routine the thread should start its execution at. For this lab, the start routine for all of our threads will be inc_count.
  • (^) arg is a pointer to the arguments passed to the start routine. Each thread start_routine is only allowed one argument. Thus, multiple arguments are packaged in a struct.

Waiting on the Threads

● (^) You'll recall from lab 3 that we used waitpid to tell the parent process to wait for its children. ● (^) We achieve similar behavior for threads with join: int pthread_join(pthread_t thread, void **value_ptr); ● (^) pthread_join will suspend execution of the calling process (or thread) until the target thread (the thread argument) has terminated. ● (^) value_ptr is a pointer to the data returned by the pthread_exit() library call. We do not use this data, so you can just pass in NULL here. ● (^) Again, use pthread_join in a for loop: for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); }

Testing the Threaded Program

● (^) Now is a good time to go ahead and test the threaded program. To run the program, use: -bash-3.2$ ./ptcount OUTER_LOOP_MAX INNER_LOOP_MAX ● (^) Where OUTER_LOOP_MAX is the number of times the outer loop in each thread should iterate, and INNER_LOOP_MAX is the number of times the inner loop in each thread should iterate. ● (^) If you created and joined the PThreads correctly, you should see something like: -bash-3.2$ ./ptcount 10 50 Thread: 0 finished. Counted: 500 Thread: 1 finished. Counted: 500 Thread: 2 finished. Counted: 500 Main(): Waited on 3 threads. Final value of count = 1500. Done. ● (^) Which is exactly what we wanted. Each thread increments the count 500 times (10*50=500) and the final value of count is 1500 because we have three threads.

Incrementing Count

● (^) Each thread updates the count using the ++ operator in C: count++; ● (^) Observe that this one line instruction in C, is actually implemented by three instructions in the x86 hardware: mov $(C_ADDR), %eax ; Move count into a register add 1, %eax ; Add 1 to count mov %eax, $(C_ADDR) ; Store count back into memory ● (^) Now, recall that each thread is sharing only one copy of count, which is loaded from memory and stored again each time the thread increments it. ● (^) While this does not explain our behavior yet, it's necessary for understanding the solution.

A Preemptive Scheduler

● (^) Recall from lecture that the Linux scheduler is preemptive. That is, the scheduler has the ability to stop a running process (with the intention of resuming it later) and replace it with another running process. ● (^) Now, imagine a scenario where the scheduler just happened to interleave our running threads in the following way: T1 T

  1. mov $(C_ADDR), %eax
  2. add 1, %eax
  3. mov %eax, $(C_ADDR) mov $(C_ADDR), %eax add 1, %eax mov %eax, $(C_ADDR)

Questions

●

To test your understanding, you should answer the

following questions:

  • (^) Why was there no inconsistency in the count when you

tested for smaller inner and outer loop bounds?

  • (^) Why are the local variables that are printed out always

consistent?

Fixing the Problem

● Regions of code that update shared data are known as

critical sections.

● In order to ensure proper synchronization between

cooperating threads, we need some way of enforcing the

property that only one thread may execute inside a critical

section at a time.

● Solution:

  • (^) Place mutex locks around critical sections.
  • (^) The operating system ensures mutual exclusion between threads executing inside code regions locked by mutex locks is enforced.