Guest User

dsxf

a guest
Dec 5th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. pthread_t tid[2];
  6. int x,step;
  7. void* thread_change_number(void *n)
  8. {
  9.     pthread_t id = pthread_self();
  10.     int i = (int)n;
  11.     //if statement to check the id of the thread
  12.     if(pthread_equal(id,tid[0]))
  13.     {
  14.         // first thread
  15.     x=x+i;
  16.         printf("inside the first thread(x+1)\n");  
  17.     printf("x= %d\n",x);
  18.     }
  19.     else
  20.     {
  21.         //second thread
  22.     x=x+i;
  23.         printf("inside the second thread(x-1)\n");
  24.         printf("x= %d\n",x);
  25.     }
  26.  
  27. }
  28.  //change number fuction
  29. int change_number(int x,int step){
  30.     return x+step;
  31. }
  32. int main(int argc, char **argv)
  33. {
  34.     printf("--beginning of program\n");
  35.     printf("give X\n");
  36.     scanf("%d",&x);
  37.     printf("x= %d\n",x);
  38.     pid_t pid = fork();
  39.     if (pid == 0)
  40.     {
  41.         // child process
  42.     x=change_number(x,2);
  43.     printf("inside child process(x+2)\n");
  44.     printf("x=%d\n",x);
  45.     //thread creation
  46.         pthread_create(&(tid[0]), NULL, &thread_change_number,(void *)1);
  47.     pthread_create(&(tid[1]), NULL, &thread_change_number,(void *)-1);
  48.     sleep(3);
  49.     }
  50.     else if (pid > 0)
  51.     {
  52.         // parent process
  53.         x=change_number(x,-1);
  54.         printf("inside parent process(x-1)\n");
  55.         printf("x=%d\n",x);
  56.     sleep(4);
  57.     }
  58.     else
  59.     {
  60.         // fork failed
  61.         printf("fork() failed!\n");
  62.         return 1;
  63.     }
  64.  
  65.     printf("\n--end of program--\n");
  66.  
  67.     return 0;
  68. }
Add Comment
Please, Sign In to add comment