C++ Windows线程等待方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/811641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:24:20  来源:igfitidea点击:

Windows Threading Wait Method

c++multithreading

提问by Sam Cogan

I'm creating a thread class to encapsulate the windows thread methods. I'm trying to create a method that makes the application wait for the thread to complete before it exits the application. If I use a while loop and boolean flag, it works but obviously it spikes my CPU use and it's just not ideal.

我正在创建一个线程类来封装 windows 线程方法。我正在尝试创建一个方法,使应用程序在退出应用程序之前等待线程完成。如果我使用 while 循环和布尔标志,它可以工作,但显然它会增加我的 CPU 使用率,而且它并不理想。

What ways would you use to wait for the completion of a thread? I'm not really looking for code here, just areas to look into.

你会用什么方式来等待线程完成?我并不是真的在这里寻找代码,只是要研究的领域。

回答by Brian R. Bondy

After you use CreateThread to get a thread handle, pass it into the Win32 API WaitForSingleObject:

使用 CreateThread 获取线程句柄后,将其传递给 Win32 API WaitForSingleObject

WaitForSingleObject(threadhandle, INFINITE);

If you do not use CreateThread (because you use another threading package), or perhaps your thread is always alive...

如果您不使用 CreateThread(因为您使用了另一个线程包),或者您的线程可能始终处于活动状态...

Then you can still use WaitForSingleObject. Just create an event first with the Win32 API CreateEvent, and wait for the event to be set with WaitForSingleObject. At the end of your thread set the event with SetEventand you can reset the event with ResetEvent.

那么你仍然可以使用WaitForSingleObject。只需先使用 Win32 API CreateEvent创建一个事件,然后等待使用 WaitForSingleObject 设置该事件。在您的线程结束时使用SetEvent设置事件,您可以使用ResetEvent重置事件。

Most threading packages though will have their own way to wait for a thread. Like in boost::threadyou can use .join() or a boost::condition.

不过,大多数线程包都有自己的等待线程的方式。就像在boost::thread 中一样,您可以使用 .join() 或boost::condition。