Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- pthread_t tid[2];
- int x,step;
- void* thread_change_number(void *n)
- {
- pthread_t id = pthread_self();
- int i = (int)n;
- //if statement to check the id of the thread
- if(pthread_equal(id,tid[0]))
- {
- // first thread
- x=x+i;
- printf("inside the first thread(x+1)\n");
- printf("x= %d\n",x);
- }
- else
- {
- //second thread
- x=x+i;
- printf("inside the second thread(x-1)\n");
- printf("x= %d\n",x);
- }
- }
- //change number fuction
- int change_number(int x,int step){
- return x+step;
- }
- int main(int argc, char **argv)
- {
- printf("--beginning of program\n");
- printf("give X\n");
- scanf("%d",&x);
- printf("x= %d\n",x);
- pid_t pid = fork();
- if (pid == 0)
- {
- // child process
- x=change_number(x,2);
- printf("inside child process(x+2)\n");
- printf("x=%d\n",x);
- //thread creation
- pthread_create(&(tid[0]), NULL, &thread_change_number,(void *)1);
- pthread_create(&(tid[1]), NULL, &thread_change_number,(void *)-1);
- sleep(3);
- }
- else if (pid > 0)
- {
- // parent process
- x=change_number(x,-1);
- printf("inside parent process(x-1)\n");
- printf("x=%d\n",x);
- sleep(4);
- }
- else
- {
- // fork failed
- printf("fork() failed!\n");
- return 1;
- }
- printf("\n--end of program--\n");
- return 0;
- }
Add Comment
Please, Sign In to add comment