[英]C++ threads: How to stop one thread from executing while other is still running (Win32)
The problem persists on Win32 environment in Visual Studio.该问题在 Visual Studio 中的 Win32 环境中仍然存在。
I have 2 classes:我有2个班级:
void classA::DoSth(HWND param){
for(int i = 0; i<24; i++)
std::cout<<i<<"\n";
}
void classB::DataGood(HWND param){
std::cout<<"OKAY\n";
}
Implemantation file: Implementation.cpp实现文件:Implementation.cpp
UINT startDAQThread(LPVOID param)
{
theApp.myClassB = new ClassB; //reference to theApp found below
theApp.myClassB->DataGood((HWND)param); //continually looks for data
return(0);
}
UINT startAlgorithmThread(LPVOID param)
{
theApp.classAPtr->DoSth((HWND)param);
return(0);
}
BOOL Implementation::OnInitDialog(){
AfxBeginThread(startDAQThread, GetSafeHwnd(), THREAD_PRIORITY_NORMAL);
Sleep(1000);
AfxBeginThread(startAlgorithmThread, GetSafeHwnd(), THREAD_PRIORITY_ABOVE_NORMAL);
return TRUE;// #define TRUE 1
}
MainApp.h主应用程序
class MainApp:public CWinApp{
MainApp();
};
extern MainApp theApp;
MainApp.cpp主应用程序
MainApp theApp;
Output:输出:
1
2
3
OKAY
4
5
OKAY
6
7
8
OKAY
9-23
How do I make sure the loop completes its run first and then some other execution?如何确保循环先完成其运行,然后再执行其他一些操作?
Research I have done:我做过的研究:
As a beginner, I did make some effort to try to add a mutex and restrict resource sharing.作为初学者,我确实努力尝试添加互斥锁并限制资源共享。 I did not succeed since I could not figure out what resource is being shared between two classes/functions
我没有成功,因为我无法弄清楚两个类/函数之间正在共享什么资源
I have made sure all #includes
are included and the program compiles and runs我已经确保包含所有
#includes
并且程序编译并运行
The ideal "shared resource" you are looking for in this case would be a condition variable - another mean of threads synchronisation.在这种情况下,您正在寻找的理想“共享资源”将是条件变量 - 线程同步的另一种方式。
You can read more about them here - https://thispointer.com/c11-multithreading-part-7-condition-variables-explained/您可以在此处阅读有关它们的更多信息 - https://thispointer.com/c11-multithreading-part-7-condition-variables-explained/
Essentially you would maintain a "flag" (ie conditional variable), that the tread that runs a loop would signal when it's done printing the numbers.本质上,您将维护一个“标志”(即条件变量),运行循环的胎面将在完成打印数字时发出信号。
The other thread will be blocked (if you synchronise them properly), until the conditional variable is signalled to be changed by the first thread.另一个线程将被阻塞(如果你正确地同步它们),直到条件变量被第一个线程通知改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.