Systems programming Thread management (Cont.) Most of the slides in - - PowerPoint PPT Presentation

systems programming
SMART_READER_LITE
LIVE PREVIEW

Systems programming Thread management (Cont.) Most of the slides in - - PowerPoint PPT Presentation

Systems programming Thread management (Cont.) Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash Creation of Unix processes vs. Pthreads Example of Pthreads #include <pthread.h>


slide-1
SLIDE 1

Systems programming

Thread management (Cont.)

Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash

slide-2
SLIDE 2

Creation of Unix processes vs. Pthreads

slide-3
SLIDE 3

Example of Pthreads

#include <pthread.h> #include <stdio.h> void *PrintHello(void * id){ printf(“Thread %d: Hello World!\n", id); } void main (){ pthread_t thread0, thread1; pthread_create(&thread0, NULL, PrintHello, (void *) 0); pthread_create(&thread1, NULL, PrintHello, (void *) 1); }

slide-4
SLIDE 4

Example of Pthreads with join

#include <pthread.h> #include <stdio.h> void *PrintHello(void * id){ printf(“Hello from thread %d\n", id); } void main (){ pthread_t thread0, thread1; pthread_create(&thread0, NULL, PrintHello, (void *) 0); pthread_create(&thread1, NULL, PrintHello, (void *) 1); pthread_join(thread0, NULL); pthread_join(thread1, NULL); }

slide-5
SLIDE 5

Compiling a Pthread program

gcc −g −Wall −o hello hello.c −lpthread

Linking the Pthreads library

slide-6
SLIDE 6

Running a Pthreads program

./hello ./hello

Hello from thread 0 Hello from thread 1 Hello from thread 1 Hello from thread 0

slide-7
SLIDE 7

Terminating Threads

  • There are several ways in which a Pthread may be terminated:
  • The thread returns from its starting routine
  • (the main routine for the initial thread).
  • The thread makes a call to the pthread_exit() subroutine.
  • The thread is canceled by another thread via

the pthread_cancel() routine

  • The entire process is terminated due to a call to either the exec() or exit()

subroutines.

slide-8
SLIDE 8

pthread_exit() - terminate calling thread

Description: terminates running a thread. Syntax: void pthread_exit(void *value_ptr);

slide-9
SLIDE 9

pthread_exit() -- Example

slide-10
SLIDE 10

pthread_self()

Syntax: pthread_t pthread_self(void);

  • The pthread_self() function returns the ID of the thread in which it is

invoked.

slide-11
SLIDE 11

pthread_self() -- Example

slide-12
SLIDE 12

pthread_equal() ()

Syntax: int pthread_equal (pthread_t t1, pthread_t t2);

  • The pthread_equal() function compares two thread identifiers. It return ‘0’

and non zero value. If it is equal then return non zero value else return 0.

slide-13
SLIDE 13

pthread_equal() () – Example 1

slide-14
SLIDE 14

pthread_equal() () – Example 2

slide-15
SLIDE 15

By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done. for(t=0;t < NUM_THREADS; t++) { pthread_join( threads[t], NULL); }

How about if if th the main th thread uses pthread_exit not pthread_jo join?

slide-16
SLIDE 16

Similar to previous but with incorrect parameters

slide-17
SLIDE 17

pthread_cancel() ()

  • The pthread_cancel() function cancels a particular thread using

thread id. This function send a cancellation request to the thread.

  • Syntax:

int pthread_cancel(pthread_t thread);

slide-18
SLIDE 18
slide-19
SLIDE 19

Thread Detach & Jo Join

  • Call pthread_join() or pthread_detach() for every thread that is

created, so that the system can release all resources associated with the thread.

  • Failure to join or to detach threads →memory and other resource

leaks until the process ends.

slide-20
SLIDE 20

Detaching a T Thread

  • Syntax:

int pthread_detach(pthread_t threadid);

  • Description: Indicate that system resources for the specified

thread should be release when the thread ends

  • If the thread is already ended, resources are release immediately
  • This routine does not cause the thread to end
  • Threads are detached
  • after a pthread_detach() call
  • after a pthread_join() call
slide-21
SLIDE 21

How to make a Thread Detached

void *processfd(void *arg); int error; int fd pthread_t tid; if (error = pthread_create(&tid, NULL, processfd, &fd)) { fprintf(stderr, "Failed to create thread: %s\n", strerror(error)); } else if (error = pthread_detach(tid)){ fprintf(stderr, "Failed to detach thread: %s\n", strerror(error)); }

slide-22
SLIDE 22

Pt Pthread Operations (r (review)

function description pthread_cancel terminate another thread pthread_create create a thread pthread_detach set thread to release resources pthread_equal test two thread IDs for equality pthread_exit exit a thread without exiting process pthread_join wait for a thread pthread_self find out own thread ID

slide-23
SLIDE 23

Thread Creation (r (review)

pthread.h pthread_t

int pthread_create ( pthread_t* thread_p /* out */ , const pthread_attr_t* attr_p /* in */ , void* (*start_routine ) ( void ) /* in */ , void* arg_p /* in */ ) ;

On One obj bject t for eac ach thread ad.

slide-24
SLIDE 24
  • Create an attribute object (initialize it with default properties)
  • Modify the properties of the attribute object
  • Create a thread using the attribute object
  • The object can be changed or reused without affecting the thread
  • The attribute object affects the thread only at the time of thread

creation

Thread Attributes

#include <pthread.h> int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t *attr);

In all the previous examples in which we used pthread_create, we passed in a null pointer instead of passing in a pointer to a pthread_attr_t structure

slide-25
SLIDE 25

Settable Properties of Thread Attributes

property function attribute objects pthread_attr_destroy pthread_attr_init

detach state

pthread_attr_getdetachstate pthread_attr_setdetachstate

stack

pthread_attr_getguardsize pthread_attr_setguardsize pthread_attr_getstack pthread_attr_setstack

scheduling

pthread_attr_getinheritsched pthread_attr_setinheritsched pthread_attr_getschedparam pthread_attr_setschedparam pthread_attr_getschedpolicy pthread_attr_setschedpolicy pthread_attr_getscope pthread_attr_setscope

slide-26
SLIDE 26

Example of creating a thread with none- default attributes: “a thread of a attribute

  • f contending other processes”

#include <pthread.h> pthread_t tid; void * myfunction(void *); void *myptr; pthread_attr_t tattr; pthread_attr_init( &tattr ); pthread_attr_setscope( &tattr, PTHREAD_SCOPE_SYSTEM ); thread_create( &tid, &tattr, myfunction, &myptr );

  • The contention scope can be

PTHREAD_SCOPE_PROCESS or PTHREAD_SCOPE_SYSTEM.

  • The scope determines whether the int

pthread_attr_setscope(pthread_attr_t *attr, int contentionscope);

  • thread competes with other threads of the

process or with other processes in the system.

slide-27
SLIDE 27

Multiplication of f Matrix using threads

slide-28
SLIDE 28

Mult ltiplication of f Matrix usin ing threads (p (part 1 of f code)

slide-29
SLIDE 29

Mult ltiplication of f Matrix usin ing threads (p (part 2 of f code)

slide-30
SLIDE 30

An example of Thread synchronization Problem

A global Variable If proper synchronization techniques are NOT applied, it may cause a RACE CONDITION where the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads.

slide-31
SLIDE 31

Race Condition Example

Thread 0 for i = 0, n/2-1 s = s + f(A[i]) Thread 1 for i = n/2, n-1 s = s + f(A[i]) int s = 0;

  • Also called critical section problem.
  • A race condition or data race occurs when:
  • two processors (or two threads) access the same variable, and at

least one does a write.

  • The accesses are concurrent (not synchronized) so they could

happen simultaneously

slide-32
SLIDE 32

Thread Mutex

Mutex = Mutual Exclusion One of the primary means of implementing thread synchronization and for protecting shared data when multiple writes occur. Acts like a lock protecting access to a shared data resource Only one thread can lock (or own) a mutex variable at any given time.

slide-33
SLIDE 33

Thread Mutex (Cont.)

  • A typical sequence in the use of a mutex is as follows:
  • 1. Create and initialize a mutex variable
  • 2. Several threads attempt to lock the mutex
  • 3. Only one succeeds and that thread owns the mutex
  • 4. The owner thread performs some set of actions
  • 5. The owner unlocks the mutex
  • 6. Another thread acquires the mutex and repeats the process
  • 7. Finally the mutex is destroyed
slide-34
SLIDE 34

Thread Mutex – Basic Operations

int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr) int pthread_mutex_lock(pthread_mutex_t *mutex) int pthread_mutex_unlock(pthread_mutex_t *mutex)

  • Initializes a mutex variable (mutex) with some attributes (attr).
  • attributes are usually NULL.

Indivisibly waits for mutex to be unlocked and then locks it. Unlocks a mutex.

slide-35
SLIDE 35
slide-36
SLIDE 36

Threads summary ry

  • Threads provide a mechanism for writing concurrent programs.
  • Threads are growing in popularity
  • Somewhat cheaper than processes.
  • Easy to share data between threads.
  • However, the ease of sharing has a cost:
  • Easy to introduce subtle synchronization errors.
  • Tread carefully with threads!
  • For more info:
  • D. Butenhof, “Programming with Posix Threads”, Addison-Wesley, 1997.