#include <stdio.h> #include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE #include <unistd.h> //getpid, getppid, fork #include <pthread.h> int g = 0; void *ProcessA_Thread2(void *vargp) { // Store the value argument passed to this thread long int *myid2 = (long int *)vargp; // Let us create a static variable to observe its changes static int s = 0; // Change static and global variables ++s; ++g; // Print the argument, static and global variables printf("%s Thread ID: %ld, Static: %d, Global: %d\n", __func__, *myid2, s, g); } void *ProcessA_Thread1(void *vargp) { // Store the value argument passed to this thread long int *myid1 = (long int *)vargp; // Let us create a static variable to observe its changes static int v = 0; // Change static and global variables ++v; ++g; // Print the argument, static and global variables printf("%s Thread ID: %ld, Static: %d, Global: %d\n", __func__, *myid1, v, g); } void create_thread() { pthread_t tid_1; pthread_t tid_2; pthread_create(&tid_1, NULL, ProcessA_Thread1, (void *)&tid_1); pthread_join(tid_1, NULL); printf("%s %d Thread ID: %ld, Global: %d\n", __func__, __LINE__, (long int)tid_1, g); pthread_create(&tid_2, NULL, ProcessA_Thread2, (void *)&tid_2); pthread_join(tid_2, NULL); printf("%s %d Thread ID: %ld, Global: %d\n", __func__, __LINE__, (long int)tid_2, g); pthread_exit(NULL); } void process_A () { printf(" Child: %s(), my pid is %d, and my parent's pid is %d\n", __func__, getpid(), getppid()); create_thread(); printf("%s %d\n",__func__, __LINE__); exit(EXIT_SUCCESS); } void parent(pid_t pid) { printf("%s(), my pid is %d, and my parent's pid is %d\n", __func__, getpid(), getppid()); exit(EXIT_SUCCESS); } int main() { pid_t pid = 0; printf("In %s\n",__func__); switch(pid = fork()) { case -1: perror("fork failed"); exit(EXIT_FAILURE); break; case 0: process_A(); break; default: /* Wait for the child processes to complete */ wait(NULL); parent(pid); break; } return 0; }
Output
In main Child: Process_A(), my pid is 11717, and my parent's pid is 11716 ProcessA_Thread1 Thread ID: 140122768467712, Static: 1, Global: 1 create_thread 44 Thread ID: 140122768467712, Global: 1 ProcessA_Thread2 Thread ID: 140122768467712, Static: 1, Global: 2 create_thread 47 Thread ID: 140122768467712, Global: 2 parent(), my pid is 11716, and my parent's pid is 5111
Comments
Post a Comment