Professional Documents
Culture Documents
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void *thread_function(void *arg) {
int i,tid;
tid=pthread_self();
for ( i=0; i<2; i++ ) {
printf("Thread with id %d says Hi!\n",tid);
sleep(1);
}
return NULL;
}
int main(void) {
pthread_t mythread1,mythread2;
if ( pthread_create( &mythread1, NULL, thread_function, NULL) ) {
printf("error creating thread!");
abort();
}
if ( pthread_create( &mythread2, NULL, thread_function, NULL) ) {
printf("error creating thread!");
abort();
}
if ( pthread_join ( mythread1, NULL ) ) {
printf("error joining thread!");
abort();
}
if ( pthread_join ( mythread2, NULL ) ) {
printf("error joining thread!");
abort();
}
printf("Main function terminates\n");
pthread_exit(NULL);
}
EXECUTION STEPS
gcc thread.c -lpthread
./a.out
OUTPUT
Thread with id 1914717952 says Hi!
Thread with id 1906325248 says Hi!
Thread with id 1914717952 says Hi!
Thread with id 1906325248 says Hi!
Main function terminates