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 操作释放出来的内存。

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

  • 相关阅读:
    lodash chunk
    lodash.slice
    ⚡ vue3 全家桶体验
    构建一个简约博皮的过程
    [译] 制作 Vue 3 的过程
    ⚠ | 不要再使用 markdown 主题了!
    win 常用命令
    2020年了,别再重复学习原型了
    删除 linux 导致原来的 win10 进不去
    手写一个文章目录插件
  • 原文地址:https://www.cnblogs.com/zendu/p/6125687.html
Copyright © 2011-2022 走看看