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

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

  • 相关阅读:
    进程的经典同步问题
    数学余数在计算机的用途
    7.货仓选址 绝对值不等式
    6. 排队打水 排序不等式
    5.合并果子 Huffman树
    4.区间覆盖 区间问题
    3.区间分组 区间问题
    2.最大不相交区间数量 区间问题
    1.区间选点 区间问题
    26.拆分-Nim游戏 博弈论
  • 原文地址:https://www.cnblogs.com/zendu/p/6125687.html
Copyright © 2011-2022 走看看