首页 > 代码库 > pthread 学习系列 case1
pthread 学习系列 case1
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 }
打印输出结果
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
可见:
1 global 在线程中可见,而且共享,
2 main中的loca通过指针传给了进程,进程可以改变
3 两个线程中的私有变量是不同的,是线程私有的。
这和fork出的进程就完全不同
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 }
打印结果:
This is the child process!10769, 7, 11 This is the parent process! child processid=1076910768, 6, 10
可见,调用fork,会有两次返回,一次是父进程、一次是子进程,因为子进程是父进程的副本,所以它拥有父进程数据空间、栈和堆的副本,它们并没有共享这些存储空间,它们只共享正文段。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。