Systems programming
Thread management
Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash
Systems programming Thread management Most of the slides in this - - PowerPoint PPT Presentation
Systems programming Thread management Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash Threads Thread Ya3ni 5ai6 A process , in the simplest terms, is an executing program. One or
Thread management
Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash
Thread Ya3ni 5ai6
A process, in the simplest terms, is an executing program. One or more threads run in the context
basic unit to which the
processor time. A thread can execute any part of the process code, including parts currently being executed by another thread
All C programs using pthreads need to include the pthread.h header file (i.e.: #include <pthread.h>). There are four steps for creating a basic threaded program:
Example: pthread_t thread0;
argument. For example: void *my_entry_function(void *param);
A void pointer can hold address of any type and can be typcasted to any type
created, we can create the thread using pthread_create.
Example: pthread_create(&thread0, NULL, my_entry_function, ¶m); If successful, the pthread_create() function returns a zero value. Otherwise, an error number is returned to indicate the error.
to join everything back up.
parameters:
(not a pointer this time)
now – just set it to NULL). Example: pthread_join(thread0, NULL);
#include <pthread.h> #include <stdio.h> /* this function is run by the second thread */ void *inc_x(void *x_void_ptr) { /* increment x to 100 */ int *x_ptr = (int *)x_void_ptr; while(++(*x_ptr) < 100); printf("x increment finished\n"); return NULL; } int main() { int x = 0, y = 0; printf("x: %d, y: %d\n", x, y); pthread_t inc_x_thread; if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) { fprintf(stderr, "Error creating thread\n"); return 1; } while(++y < 100); printf("y increment finished\n"); if(pthread_join(inc_x_thread, NULL)) { fprintf(stderr, "Error joining thread\n"); return 2; } /* show the results - x is now 100 thanks to the second thread */ printf("x: %d, y: %d\n", x, y); return 0; } x: 0, y: 0 y increment finished x increment finished x: 100, y: 100