重新开帖,高分求救,线程同步WaitFor问题,,急!!

fidt982 2005-01-12 04:05:58
下面这段代码BUTTON单击后为什么会报错,说句柄无效


***************unit1.h-------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
--------------------------

************unit1.cpp------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
MyThread *thread;
thread=new MyThread(false);
if(thread->WaitFor()==0)
ShowMessage("return");
}

***************unit2.h-----------------
class MyThread : public TThread
{
private:
protected:
void __fastcall Execute();
public:
__fastcall MyThread(bool CreateSuspended);
};


***********unit2.cpp----------------
__fastcall MyThread::MyThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall MyThread::Execute()
{
//---- Place thread code here ----
FreeOnTerminate=true;
ReturnValue=255;
int sum;
for(int i=0;i<200000;i++)
sum+=i;
ReturnValue=0;

}
...全文
63 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
fidt982 2005-01-12
  • 打赏
  • 举报
回复
结了,,
3996906 2005-01-12
  • 打赏
  • 举报
回复
看见没有,我注释掉的这句是结束后释放的

想一下你都已经释放资源了在Unit1里的thread已经为空了,句柄当然无效
3996906 2005-01-12
  • 打赏
  • 举报
回复
很简单

__fastcall MyThread::MyThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall MyThread::Execute()
{
//---- Place thread code here ----
//FreeOnTerminate=true;
ReturnValue=255;
int sum;
for(int i=0;i<200000;i++)
sum+=i;

ReturnValue=0;
}

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧