zoukankan      html  css  js  c++  java
  • 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.
    ");
    16     
    17    strcpy(str,"Changed by a thread!
    ");
    18    return ((void *)0);
    19 }
    20 
    21 int main(void)
    22 {
    23     int err;
    24     int fd;
    25     char parent[100] = "I am parent!
    "; 
    26 
    27     fd = open("log.txt",O_CREAT|O_WRONLY);
    28     if(-1 == fd)
    29     {
    30     printf("Failed to open  file!
    ");
    31     }
    32 
    33     err = pthread_create(&ntid,NULL,thr_fn,parent);
    34     if(err != 0)
    35     {
    36     printf("can't create thread ,errno = %d
    ",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!
    ");
    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。

    学习记录,方便复习
  • 相关阅读:
    Otter详解
    为什么要使用Netty
    haproxy实现mysql集群负载均衡
    Mysql主从复制
    java编程思想读书笔记三(HashMap详解)
    代码界的石器时代
    补码的产生与应用
    java编程思想读书笔记二(对象的创建)
    java编程思想读书笔记一(面向对象)
    Apache VFS
  • 原文地址:https://www.cnblogs.com/jingjingdidunhe/p/6349614.html
Copyright © 2011-2022 走看看