+ -
当前位置:首页 → 问答吧 → ccrun请帮帮忙看看呗。c++ builder 线程 频繁的创建 有时抛出异常;单/多核运行情况不一样;优先级

ccrun请帮帮忙看看呗。c++ builder 线程 频繁的创建 有时抛出异常;单/多核运行情况不一样;优先级

时间:2011-12-23

来源:互联网

情况:
线程1:
__fastcall Time_slice::Time_slice(bool CreateSuspended,unsigned int mypagecount)
  : TThread(CreateSuspended)
{
  FreeOnTerminate = true;//线程结束后自动释放空间
  Priority = tpHighest; //中高优先级
  iPageCount = mypagecount;
}
//---------------------------------------------------------------------------

void __fastcall Time_slice::Execute()
{
  //---- Place thread code here ----
  while(!Terminated)
  {
  unsigned int temp;
  switch (iPageCount)
  {
  case 1 :
  temp = MyCOM->Process(cSendPulse, 14);
  PostThreadMessage(myUI_Set_Thread->ThreadID,9999,temp,0);
  break;
  case 0 :
  break;
  default :
  ;  
  }
  Terminate();
  }
}
//------------------------------------------------------------------------------


线程2:

__fastcall UI_Set_Thread::UI_Set_Thread(bool CreateSuspended)
  : TThread(CreateSuspended)
{
  FreeOnTerminate = true;//线程结束后自动释放空间
  Priority = tpHighest; //中高优先级
}
//---------------------------------------------------------------------------
void __fastcall UI_Set_Thread::Execute()
{
  //---- Place thread code here ----
  while(!Terminated)
  {
  GetMessage(&mymsg,0,9999,10000);
  Synchronize(Message_1_Result);
  }
}
void __fastcall UI_Set_Thread::Message_1_Result()
{
  if(mymsg.message == 9999)
  {
  MainForm->Button1->Enabled = true;
  MainForm->RichEdit->Perform(EM_SCROLLCARET, 0, 0);
  bSysIsBusy = false;
  }

按钮事件:
void __fastcall TMainForm::FormShow(TObject *Sender)
{
  myUI_Set_Thread = new UI_Set_Thread(true); //界面处理线程
  myUI_Set_Thread->Resume();

void __fastcall TMainForm::Button1Click(TObject *Sender)

  if(bSysIsBusy == false)
  {
   
  bSysIsBusy = true;
  Button1->Enabled = false;
  try
  {
  myTime_slice = new Time_slice(true,1);
  }
  catch(Exception &exception)
  {  
  Application->MessageBox("线程创建异常", NULL, MB_OK);
  bSysIsBusy = false;
  Button1->Enabled = true;
  }
  }  

问题:在双核cpu上。不断单击button1按钮改程序运行正常。单核cpu上,不断单击button1按钮创建线程有时程序抛出异常。将线程1优先级 Priority = tpHighest; //中高优先级注释掉后,没有抛出异常;将线程2的处理放到线程1用Synchronize处理,也没有异常。问为什么?
补充:在按钮事件里将button enabled关闭,在线程2中将button1 enabled打开。
另外用这种模式好吗,即将所有的vcl处理放到一个单独的线程。别的线程只要发送消息到此线程 就可以了。想要做一件事只要在按钮事件里创建个线程。线程设定为自动释放。

作者: fan601428   发布时间: 2011-12-23

将所有的vcl处理放到主线程

作者: lhylhy   发布时间: 2011-12-23

热门下载

更多