Tutorial4 Threads

75 %
25 %
Information about Tutorial4 Threads

Published on November 10, 2007

Author: tech2click

Source: slideshare.net

Threads

Process Processes contain information about program resources and program execution state, including: Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers Stack Heap File descriptors Signal actions Shared libraries Inter-process communication tools (such as message queues, pipes, semaphores, or shared memory).

Processes contain information about program resources and program execution state, including:

Process ID, process group ID, user ID, and group ID

Environment

Working directory.

Program instructions

Registers

Stack

Heap

File descriptors

Signal actions

Shared libraries

Inter-process communication tools (such as message queues, pipes, semaphores, or shared memory).

UNIX Process

Threads Threads use and exist within these process resources, yet are able to be scheduled by the operating system and run as independent entities largely because they duplicate only the bare essential resources that enable them to exist as executable code.

Threads use and exist within these process resources, yet are able to be scheduled by the operating system and run as independent entities largely because they duplicate only the bare essential resources that enable them to exist as executable code.

Cont. This independent flow of control is accomplished because a thread maintains its own: Stack pointer Registers Scheduling properties (such as policy or priority) Set of pending and blocked signals Thread specific data (thread ID)

This independent flow of control is accomplished because a thread maintains its own:

Stack pointer

Registers

Scheduling properties (such as policy or priority)

Set of pending and blocked signals

Thread specific data (thread ID)

UNIX Thread

UNIX Threads In the UNIX environment a thread: Exists within a process and uses the process resources Has its own independent flow of control as long as its parent process exists and the OS supports it Duplicates only the essential resources it needs to be independently schedulable May share the process resources with other threads that act equally independently (and dependently) Dies if the parent process dies - or something similar Is "lightweight" because most of the overhead has already been accomplished through the creation of its process.

In the UNIX environment a thread:

Exists within a process and uses the process resources

Has its own independent flow of control as long as its parent process exists and the OS supports it

Duplicates only the essential resources it needs to be independently schedulable

May share the process resources with other threads that act equally independently (and dependently)

Dies if the parent process dies - or something similar

Is "lightweight" because most of the overhead has already been accomplished through the creation of its process.

Pthreads A thread library that provides the programmer an API for creating and managing threads Pthreads refers to the POSIX standards defining an API for thread creation and synchronization

A thread library that provides the programmer an API for creating and managing threads

Pthreads refers to the POSIX standards defining an API for thread creation and synchronization

Pthreads Pthreads are defined as a set of C language programming types and procedure calls, implemented with a pthread.h header/include file and a thread library

Pthreads are defined as a set of C language programming types and procedure calls, implemented with a pthread.h header/include file and a thread library

Creating threads Initially, your main() program comprises a single, default thread. All other threads must be explicitly created by the programmer.

Initially, your main() program comprises a single, default thread. All other threads must be explicitly created by the programmer.

Creating threads (cont.) int pthread_create (pthread_t * thread , const pthread_attr_t * attr , void *(* start_routine ) (void*), void * arg ); Description: pthread_create() creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code.

int pthread_create (pthread_t * thread , const pthread_attr_t * attr , void *(* start_routine ) (void*), void * arg );

Description:

pthread_create() creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code.

Creating threads (cont.) pthread_create() arguments: thread: An opaque, unique identifier for the new thread returned by the subroutine. attr: An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. start_routine: the C routine that the thread will execute once it is created. arg: A single argument that may be passed to start_routine . It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.

pthread_create() arguments:

thread: An opaque, unique identifier for the new thread returned by the subroutine.

attr: An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values.

start_routine: the C routine that the thread will execute once it is created.

arg: A single argument that may be passed to start_routine . It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.

Cont. Return value: If successful, the pthread_create() routine shall return zero other- wise, an error number shall be returned to indicate the error.

Return value:

If successful, the pthread_create() routine shall return zero

other- wise, an error number shall be returned to indicate the error.

Thread attributes Thread attributes include (define members of the struct pthread_attr_t): detached state scheduling policy scheduling parameter inheritsched attribute Scope guard size stack address stack size

Thread attributes include (define members of the struct pthread_attr_t):

detached state

scheduling policy

scheduling parameter

inheritsched attribute

Scope

guard size

stack address

stack size

Scheduling threads After a thread has been created, how do you know when it will be scheduled to run by the operating system? It is up to the implementation and/or operating system to decide where and when threads will execute.

After a thread has been created, how do you know when it will be scheduled to run by the operating system?

It is up to the implementation and/or operating system to decide where and when threads will execute.

Terminating threads pthread_exit() is used to explicitly exit a thread. If main() finishes before the threads it has created, and exits with pthread_exit() , the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

pthread_exit() is used to explicitly exit a thread.

If main() finishes before the threads it has created, and exits with pthread_exit() , the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

Joining Threads int pthread_join (pthread_t thread, void **value_ptr); Description: The pthread_join() function shall suspend execution of the calling thread until the target thread terminates. Return value: If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.

int pthread_join (pthread_t thread, void **value_ptr);

Description:

The pthread_join() function shall suspend execution of the calling thread until the target thread terminates.

Return value:

If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.

Joining Threads (Cont.)

Example -1-

#include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d! &quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d &quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc); exit(-1); } } pthread_exit(NULL);}

#include <pthread.h>

#include <stdio.h>

#define NUM_THREADS 5

void *PrintHello(void *threadid)

{

int tid;

tid = (int)threadid;

printf(&quot;Hello World! It's me, thread #%d! &quot;, tid);

pthread_exit(NULL);

}

int main (int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int rc, t;

for(t=0; t<NUM_THREADS; t++){

printf(&quot;In main: creating thread %d &quot;, t);

rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);

if (rc){

printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc);

exit(-1);

}

}

pthread_exit(NULL);}

Code Explanation

Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t In for loop: Threads will be created using pthread_create . The routine PrintHello() is the starting routine for all newly created threads The returned value for each thread creation will be checked and prints and error message if the returned value is not zero int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d &quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc); exit(-1); } }

Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t

In for loop:

Threads will be created using pthread_create . The routine PrintHello() is the starting routine for all newly created threads

The returned value for each thread creation will be checked and prints and error message if the returned value is not zero

int main (int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int rc, t;

for(t=0; t<NUM_THREADS; t++){

printf(&quot;In main: creating thread %d &quot;, t);

rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);

if (rc){

printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc);

exit(-1);

}

}

Cont. The routine PrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d! &quot;, tid); pthread_exit(NULL); }

The routine PrintHello will simply print,

“ Hello World! It’s me, thread# threadnum

It will then terminate the thread using pthread_exit.

void *PrintHello(void *threadid)

{

int tid;

tid = (int)threadid;

printf(&quot;Hello World! It's me, thread #%d! &quot;, tid);

pthread_exit(NULL);

}

Possible Outputs In main: creating thread 0 In main: creating thread 1 Hello World! It's me, thread#0! In main: creating thread 2 Hello World! It's me, thread #1! Hello World! It's me, thread #2! In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread #3! Hello World! It's me, thread #4! In main: creating thread 0 In main: creating thread 1 In main: creating thread 2 In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread#0! Hello World! It's me, thread #1! Hello World! It's me, thread #2! Hello World! It's me, thread #3! Hello World! It's me, thread #4!

In main: creating thread 0

In main: creating thread 1

Hello World! It's me, thread#0!

In main: creating thread 2

Hello World! It's me, thread #1!

Hello World! It's me, thread #2!

In main: creating thread 3

In main: creating thread 4

Hello World! It's me, thread #3!

Hello World! It's me, thread #4!

In main: creating thread 0

In main: creating thread 1

In main: creating thread 2

In main: creating thread 3

In main: creating thread 4

Hello World! It's me, thread#0!

Hello World! It's me, thread #1!

Hello World! It's me, thread #2!

Hello World! It's me, thread #3!

Hello World! It's me, thread #4!

Example -2-

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_function( void *ptr ); main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d &quot;,iret1); printf(&quot;Thread 2 returns: %d &quot;,iret2); exit(0); } void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf(&quot;%s &quot;, message); }

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_function( void *ptr );

main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL);

printf(&quot;Thread 1 returns: %d &quot;,iret1); printf(&quot;Thread 2 returns: %d &quot;,iret2); exit(0); }

void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf(&quot;%s &quot;, message); }

Code Explanation

Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t Threads will be created using pthread_create() . The routine print_message_function() is the starting routine for the two newly created routines. Notice that an argument was sent to print_message_function() as an argument to pthread_create() The two threads newly created will be joined using pthread_join() main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d &quot;,iret1); printf(&quot;Thread 2 returns: %d &quot;,iret2); exit(0); }

Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t

Threads will be created using pthread_create() . The routine print_message_function() is the starting routine for the two newly created routines. Notice that an argument was sent to print_message_function() as an argument to pthread_create()

The two threads newly created will be joined using pthread_join()

main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); pthread_join( thread1, NULL); pthread_join( thread2, NULL);

printf(&quot;Thread 1 returns: %d &quot;,iret1); printf(&quot;Thread 2 returns: %d &quot;,iret2); exit(0); }

Cont. The routine PrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void * print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf &quot;, message); } (&quot;%s

The routine PrintHello will simply print,

“ Hello World! It’s me, thread# threadnum

It will then terminate the thread using pthread_exit.

void * print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf &quot;, message); } (&quot;%s

Output Thread 1 Thread 2 Thread 1 returns : 0 Thread 2 returns : 0

Thread 1

Thread 2

Thread 1 returns : 0

Thread 2 returns : 0

Example -3- Example 1 while using pthread_join()

#include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d! &quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d &quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc); exit(-1); } pthread_join(threads[t], NULL) ;} pthread_exit(NULL);}

#include <pthread.h>

#include <stdio.h>

#define NUM_THREADS 5

void *PrintHello(void *threadid)

{

int tid;

tid = (int)threadid;

printf(&quot;Hello World! It's me, thread #%d! &quot;, tid);

pthread_exit(NULL);

}

int main (int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int rc, t;

for(t=0; t<NUM_THREADS; t++){

printf(&quot;In main: creating thread %d &quot;, t);

rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);

if (rc){

printf(&quot;ERROR; return code from pthread_create() is %d &quot;, rc);

exit(-1);

}

pthread_join(threads[t], NULL) ;}

pthread_exit(NULL);}

Possible Outputs In main: creating thread 0 Hello World! It's me, thread#0! In main: creating thread 1 Hello World! It's me, thread #1! In main: creating thread 2 Hello World! It's me, thread #2! In main: creating thread 3 Hello World! It's me, thread #3! In main: creating thread 4 Hello World! It's me, thread #4!

In main: creating thread 0

Hello World! It's me, thread#0!

In main: creating thread 1

Hello World! It's me, thread #1!

In main: creating thread 2

Hello World! It's me, thread #2!

In main: creating thread 3

Hello World! It's me, thread #3!

In main: creating thread 4

Hello World! It's me, thread #4!

Example -4-

#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } pthread_join( thread, NULL ); exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }

#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } pthread_join( thread, NULL ); exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL;

}

Output a b a a b a b a b b a b What happens if we change the position of pthread_join() in the code?

a

b

a

a

b

a

b

a

b

b

a

b

What happens if we change the position of pthread_join() in the code?

#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); pthread_join( thread, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } /* Previous position in code pthread_join( thread, NULL ); */ exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }

#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); pthread_join( thread, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } /* Previous position in code

pthread_join( thread, NULL ); */ exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b &quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL;

}

Output b b b b b b a a a a a a What happened?

b

b

b

b

b

b

a

a

a

a

a

a

What happened?

Add a comment

Related presentations

Related pages

Tutorial4 Threads - Documents

1.Threads 2. Process Processes contain information about program resources and program execution state, including:Process ID, process group ID, user ID ...
Read more

A Threads Tutorial - ResearchGate

A Threads Tutorial. Thomas W Doeppner. 01/1988; 0 ... RT++ --- Higher Order Threads for C++ Tutorial and Reference Manual (Version 1.0)
Read more

x360ce Libraries Tutorial by resolutespider5 | NGEmu

x360ce Libraries Tutorial By ResoluteSpider5. V4 December 2013. What is x360ce and how to use it contains additional information. x360ce App Tutorial at...
Read more

Frage zu HDRI und compositing | tutorials.de - User helfen ...

... http://www.ict.usc.edu/graphics/HDRShop/tutorial/tutorial4.html Nur wird dann wenn ich es umwandeln will in ein Latitude/Longitude , ...
Read more

HDRI-Problem | tutorials.de - User helfen Usern

Und zwar folgendes: Hab mir ne *.HDR-Datei runtergeladen und wollte sie in max 6 als umgebung einsetzen. Ich drücke die Taste "8" und dann bei...
Read more

Autodesk Inventor beginner tutorial: Part 1 - Modeling ...

Learn how to design a scooter with Autodesk Inventor by starting with modeling the tire using two different approaches. Part Features covered ...
Read more

C# Tutorials - msdn.microsoft.com

The C# tutorials provide an overview of the basics of the language and identify important language features. Each tutorial includes one or more sample ...
Read more

Photoshop Tutorials and Flash Tutorials - Tutorialized

Directory of tutorials for software programs such as MS Excel and Macromedia Dreamweaver.
Read more