#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 操作释放出来的内存。
我想说的是,程序的指针内存被释放后,与指针相关的运行函数并不会结束,函数所引用的内存数据会被修改,多线程程序编写时要注意这一点。