Unix 线程改变创建进程中变量的值(2)

执行环境: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。

 

转载于:https://www.cnblogs.com/jingjingdidunhe/p/6349614.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值