download report

Transcript Multithreading

Professor: Shu-Ching Chen TA: Hsin-Yu Ha

  An independent stream of instructions that can be scheduled to run A path of execution

Single-Thread Multi-Thread

int a, b; int c; a = 1; b = a + 2; c = 3; int a, b; a = 1; b = a + 2; int c; c = 5; CPU CPU

  Program  An execution file stored in the harddrive Process   An execution file stored in the Memory Thread  An execution path of part of the process

Program Process Memory HDD Thread

    Parallel execution Shared resources Easier to create and destroy than processes (100X) Easy porting to multiple CPUs

  Standardized C language threads programming interface for UNIX systems Four major groups  Thread management: Routines that work directly on threads - creating, detaching, joining, etc.  Mutex: Routines that deal with synchronization. Mutex functions provide for creating, destroying, locking and unlocking mutexes.

Condition variable: Routines that address communications between threads that share a mutex.

Synchronization: Routines that manage read/write locks and barriers.

 pthread_create() on error Return 0 if OK, nonzero  ▪ ▪ ▪ ▪ Four Arguments Thread : A thread identifier Attr : A pointer to a thread attribute object Start_routine : A pointer to the function the thread executes Arg : The argument to the function

 Single variable

 Several variables

 pthread_exit() error Return 0 if OK, nonzero on       Four ways of terminating a thread The thread returns from its starting routine The thread makes a call to the pthread_exit subroutine The thread is canceled by another thread The entire process is terminated If main() finishes first, without calling pthread_exit

 Example of pthread_exit()

 pthread_join() error Return 0 if OK, nonzero on  Wait from other threads to terminate by calling it

   pthread_self()  It returns the unique, system assigned thread ID of the calling thread pthread_detach() Return 0 if OK, nonzero on error It can be used to explicitly detach a thread

   Join Mutexes Condition variables

   Mutexes are used to prevent data inconsistencies due to operations by multiple threads upon the same memory area performed at the same time to prevent race conditions where an order of operation upon the memory is expected

   Condition variables are used to allow threads to synchronize based upon the actual value of data without continually polling to check whether the condition if met in conjunction with a mutex lock

  POSIX Threads Programming  Pthreads primer   er.html

POSIX thread (pthread) Tutorial

 alPosixThreads.html

 Tutorial -

Wiki  Tutorial and sample code

C++ Multithreading

Multithreading pthread

Posix threads C


Code project  Tutorial Youtube Video -

C++ Multithreading Pt. 1 -

C++ Multithreading Pt. 2