Programming Assignment 2
Programming Assignment 2
What is thread?
A thread is a semi-process, that has its own stack, and executes a given piece of code.
Unlike a real process, the thread normally shares its memory with other threads
(where as for processes we usually have a different memory area for each one of
them). A Thread Group is a set of threads all executing inside the same process. They
all share the same memory, and thus can access the same global variables, same heap
memory, same set of file descriptors, etc. All these threads execute in parallel (i.e.
using time slices, or if the system has several processors, then really in parallel).
Why pthreads?
#include <stdio.h>
#include <pthread.h>
void *childfunc(void *p) {
printf ("child ID is ---> %d\n", getpid( ));
}
main ( ) {
pthread_t child1,child2 ;
pthread_create (&child1, NULL, childfunc, NULL) ;
pthread_create (&child2, NULL, childfunc, NULL) ;
printf ("Parent ID is ---> %d\n", getpid( )) ;
pthread_join (child1, NULL) ;
pthread_join (child2, NULL) ;
printf ("No more children!\n") ;
}
Are the process id numbers of parent and child thread the same or different?
#include <pthread.h>
int glob_data = 5 ;
void *childfunc(void *p) {
printf ("child here. Global data was %d.\n", glob_data) ;
glob_data = 15 ;
printf ("child Again. Global data was now %d.\n", glob_data) ;
}
main ( ) {
pthread_t child1 ;
pthread_create (&child1, NULL, childfunc, NULL) ;
printf ("Parent here. Global data = %d\n", glob_data) ;
glob_data = 10 ;
pthread_join (child1, NULL) ;
printf ("End of program. Global data = %d\n", glob_data) ;
}
In this lab, we create two threads. Each one executes a 5 steps for loop that print
numbers from 0 to 4.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>