1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <pthread.h> 5 6 7 void *thread_foo_func(void *); 8 void *thread_bar_func(void *); 9 10 11 int global = 4;12 13 14 int main(){15 int local = 8;16 int foo, bar;17 pthread_t fthread, bthread;18 foo = pthread_create(&fthread, NULL, thread_foo_func, (void *)&local);19 bar = pthread_create(&bthread, NULL, thread_bar_func, (void *)&local);20 if (foo != 0 || bar != 0){21 printf("thread creation failed.\n");22 return -1;23 }24 25 26 foo = pthread_join(fthread, NULL);27 bar = pthread_join(bthread, NULL);28 if (foo != 0 || bar != 0){29 printf("thread join failed.\n");30 return -2; 31 }32 33 34 printf("In thread main");35 printf("address of global %d: %x\n", global, &global);36 printf("address of main local %d: %x\n", local, &local);37 38 return 0;39 }40 41 42 void *thread_foo_func(void *arg){43 int foo_local = 16;44 global ++;45 *(int *)arg = 10;46 printf("In thread foo_func");47 printf("address of global %d: %x\n", global, &global);48 printf("address of main local %d: %x\n", *(int *)arg, arg);49 printf("address of foo local: %x\n", &foo_local);50 printf("\n");51 }52 53 54 void *thread_bar_func(void *arg){55 int bar_local = 32;56 global ++;57 *(int *)arg = 20;58 printf("In thread bar_func");59 printf("address of global %d: %x\n", global, &global);60 printf("address of main local %d: %x\n", *(int *)arg, arg);61 printf("address of bar local: %x\n", &bar_local);62 printf("\n");63 }
Print Output results
In thread foo_funcaddress of global 5: 8049a48address of main local 10: bfc567b8address of foo local: b7f553c4In thread bar_funcaddress of global 6: 8049a48address of main local 20: bfc567b8address of bar local: b75543c4In thread mainaddress of global 6: 8049a48address of main local 20: bfc567b8
Visible:
1. Global threads are visible and shared,
2. The loca in main passes the pointer to the process and the process can be changed.
3. The private variables in the two threads are different. They are private variables in the thread.
This is totally different from the fork process.
1 int global = 6; 2 3 int main(int argc,char** argv) 4 { 5 int var=10; 6 int pid=fork(); 7 if(pid==-1){ 8 printf("error!"); 9 } 10 else if(pid==0){11 global++;12 var++;13 printf("This is the child process!\n");14 } 15 else{16 printf("This is the parent process! child processid=%d\n",pid);17 } 18 printf("%d, %d, %d \n", getpid(), global, var); 19 20 return 1; 21 }
Print result:
This is the child process!10769, 7, 11 This is the parent process! child processid=1076910768, 6, 10
It can be seen that the fork call will return two times, one being the parent process and the other being the child process because the child process is a copy of the parent process, therefore, it has the data space, stack, and heap copies of the parent process. They do not share these buckets. They only share the body segment.