如何在一个函数中终止另一个函数的运行
#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\n",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 \n",t);
t->run();
}
int main()
{
printf("%p\n",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 操作释放出来的内存。
我想说的是,程序的指针内存被释放后,与指针相关的运行函数并不会结束,函数所引用的内存数据会被修改,多线程程序编写时要注意这一点。
posted on 2016-12-02 14:35 zyz913614263 阅读(726) 评论(0) 收藏 举报
浙公网安备 33010602011771号