执行环境:Linux ubuntu 4.4.0-31-generic #50-Ubuntu SMP Wed Jul 13 00:07:12 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
1.测试代码: a.c
1 #include <fcntl.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <pthread.h> 5 #include <string.h> 6 7 pthread_t ntid; 8 9 void * thr_fn(void * arg) 10 { 11 int * fp = (int *)arg; 12 char * str = (char *)arg; 13 14 printf("I am a thread,receive a string:%s",str); 15 printf("Now,I will change it‘s value.\n"); 16 17 strcpy(str,"Changed by a thread!\n"); 18 return ((void *)0); 19 } 20 21 int main(void) 22 { 23 int err; 24 int fd; 25 char parent[100] = "I am parent!\n"; 26 27 fd = open("log.txt",O_CREAT|O_WRONLY); 28 if(-1 == fd) 29 { 30 printf("Failed to open file!\n"); 31 } 32 33 err = pthread_create(&ntid,NULL,thr_fn,parent); 34 if(err != 0) 35 { 36 printf("can‘t create thread ,errno = %d\n",err); 37 } 38 39 void ** pr; 40 err = pthread_join(ntid,pr); 41 if(err !=0 ) 42 { 43 printf("error happend when waited a thread!\n"); 44 } 45 printf("In process,the value of the string is %s",parent); 46 return 0; 47 }
2.输出:
I am a thread,receive a string:I am parent! Now,I will change it‘s value. In process,the value of the string is Changed by a thread!
3.创建进程是通过指针传递参数给线程的,线程又是共享创建进程的一些资源的,可以改变进程的变量值。
php 在创建线程的时候,线程对象需要保存进程传递进来参数的值的方式是传值,如果在构造函数中,引用传递进来的参数,会报错误:
Fatal error: Cannot assign by reference to overloaded object。
时间: 2024-10-25 11:39:26