multithreading - [C++,windows窗体]如何让主线程等待被调用线程完成?
问题描述
我创建了 2 个按钮,一个用于启动新线程,另一个用于结束它。新线程内部的实际计算涉及 new[] 和 delete[] 所以我不直接中止线程,而是使用标志来结束它。结束 delete[] 和结果保存可能需要一些时间,所以我希望主线程等待新线程结束。但是无论我怎么尝试,我发现新线程不会运行(尽管它的 ThreadState 正在运行),直到执行停止按钮的命令行。System::Threading::Thread 的工作方式与我的线程完全不同。它应该是怎样的?
#include "stdafx.h"
ref class Form1 : System::Windows::Forms::Form
{
public:
//define a thread name and a flag to terminate the thread
System::Threading::Thread^ th1;
static bool ITP1=0;
Form1(void)
{InitializeComponent();}
System::Windows::Forms::Button^ ButtonStart;
System::Windows::Forms::Button^ ButtonStop;
System::Windows::Forms::Label^ Label1;
void InitializeComponent(void)
{
this->SuspendLayout();
this->ButtonStart = gcnew System::Windows::Forms::Button();
this->ButtonStart->Location = System::Drawing::Point(20, 20);
this->ButtonStart->Click += gcnew System::EventHandler(this, &Form1::ButtonStart_Click);
this->Controls->Add(this->ButtonStart);
this->ButtonStop = gcnew System::Windows::Forms::Button();
this->ButtonStop->Location = System::Drawing::Point(120, 20);
this->ButtonStop->Click += gcnew System::EventHandler(this, &Form1::ButtonStop_Click);
this->Controls->Add(this->ButtonStop);
this->Label1 = gcnew System::Windows::Forms::Label();
this->Label1->Location = System::Drawing::Point(20, 80);
this->Controls->Add(this->Label1);
this->ResumeLayout(false);
}
void ThreadStart()
{
for (int idx=0;idx<999999999;++idx)
{
if (ITP1) break;
}
this->Label1->Text = "finished";
ITP1=0;
}
System::Void ButtonStart_Click(System::Object^ sender, System::EventArgs^ e)
{
th1 = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this,&Form1::ThreadStart));
th1->Start();
this->Label1->Text = "running";
}
System::Void ButtonStop_Click(System::Object^ sender, System::EventArgs^ e)
{
if (th1->ThreadState==System::Threading::ThreadState::Running)
{
//use the flag to stop the thread
ITP1=1;
//the wait method using while+sleep doesn't work
while (th1->ThreadState==System::Threading::ThreadState::Running) System::Threading::Thread::Sleep(1000);
//replacing the wait method above with "th1->Join()" doesn't work either
}
}
};
int main()
{
Form1^ A1 = gcnew Form1();
A1->ShowDialog();
return 0;
}
解决方案
您必须join()
在主线程中调用线程。然后主线程将一直等待,直到被调用的线程完成。
请参阅文档Join
以了解如何调用它。
推荐阅读
- bash - Bash Shell:如何按最后一列的值排序,但忽略文件的标题?
- flask - 以正确的方式构建 Flask 项目(无蓝图)
- css - 使用 React 的多个样式表问题
- asp.net - BLAZOR + MVC - 将数据从 Blazor 页面传递到 MVC 控制器
- java - Spring Data JPA 太慢了
- spring - spring-boot-test 与 spring-boot-starter-test 有什么区别?
- r - 如何将列表变成数据名(由 ID 匹配)?
- ssl - uk.co.threefi.kafka-connect-http 是否支持 SSL 连接
- php - 在 laravel 中重置密码自定义验证问题
- jquery - Wordprees OceanWP 问题。jquery“$ 不是函数”