zoukankan      html  css  js  c++  java
  • 如何在一个函数中终止另一个函数的运行

    #include <cstdio>
    #include <iostream>
    #include <vector>
    #include <map>
    #include <time.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string>
    #include <unistd.h>
    #include <pthread.h>
    
    using namespace std;
    
    class Temp
    {
    public:
        Temp(string _v) { v = _v;}
        string v;
        void run()
        {
            while(true)
            {
                printf("%p %s
    ",this,v.c_str());
                sleep(1);
            }
        }
    };
    
    Temp *t = new Temp("hello");
    
    void *fun(void *)
    {
        t->run();
    }
    
    void *fun1(void *)
    {
        sleep(1);
        delete t;
        t = NULL;
        t = new Temp("world");
        printf("t = %p 
    ",t);
    	t->run();
    }
    
    int main()
    {
        printf("%p
    ",t);
        pthread_t th1,th2;
        pthread_create(&th1,NULL,fun,NULL);
        pthread_create(&th2,NULL,fun1,NULL);
        pthread_join(th1,NULL);
        pthread_join(th2,NULL);
    }
    

      先来看这个有意思的程序,结果可以先猜一下。

    不同的编译器运行结果可能会不同,这个跟内存分配有关。较老的编辑器,相同类型的new 操作,回重用上边delete 操作释放出来的内存。

    我想说的是,程序的指针内存被释放后,与指针相关的运行函数并不会结束,函数所引用的内存数据会被修改,多线程程序编写时要注意这一点。

  • 相关阅读:
    mysql服务的注册,启动、停止、注销。 [delphi代码实现]
    java初始化
    git的使用
    jmeter测试
    Linux上安装Redis
    java多线程
    设计模式之装饰着模式
    IO流之字符流知识总结
    IO流之字节流知识总结
    java File类
  • 原文地址:https://www.cnblogs.com/zendu/p/6125687.html
Copyright © 2011-2022 走看看