简体   繁体   English

等待线程

[英]Waiting for threads

I'm using CreateThread() for my 4 threads. 我正在为我的4个线程使用CreateThread()。
I would like to run all my threads simultaneously, but wait for all 4 to finish before continuing with the main thread. 我想同时运行我的所有线程,但在继续主线程之前等待所有4个线程完成。

I used an int and increased it at the start of the thread, then decreased it at the end, then in my main thread I used a while loop to hold while the number is over a certain value... however this didn't seem to work correctly. 我使用了一个int并在线程的开头增加了它,然后在结束时减少了它,然后在我的主线程中我使用了while循环来保持数字超过某个值...但是这似乎没有工作正常。

Is this possible? 这可能吗?

Use WaitForMultipleObjects with the bWaitAll flag set, on all of your thread handles. 在所有线程句柄上使用设置了bWaitAll标志的WaitForMultipleObjects The function will return once all threads exit. 所有线程退出后,该函数将返回。

You can use the mechanism of signaled states and the WaitForMultipleObjects function to wait for the events or threads themselves (pointed to by their handles) to reach a signalled state. 您可以使用信号状态机制和WaitForMultipleObjects函数来等待事件或线程本身(由其句柄指向)以达到信号状态。

By simply sharing a single variable among those threads you're probably running into synchronization problems, especially when they are spread among your CPU's cores. 通过简单地在这些线程中共享单个变量,您可能会遇到同步问题,尤其是当它们分布在CPU的核心中时。

If you want to modify a shared value atomically without using synchronization mechanisms, use the "Interlocked*" functions like InterlockedIncrement , although that doesn't completely guarantee that there will be no problems. 如果要修改一个共同的价值原子,而不使用同步机制,使用像“联锁*”功能InterlockedIncrement ,虽然这并不能完全保证不会有问题。 Don't use that method as a synchronization mechanism anyway. 不管怎样,不要将该方法用作同步机制。

If you want that your main thread waits until all the child threads complete their job then You can use: 如果您希望主线程等待所有子线程完成其工作,那么您可以使用:

pthread_join 在pthread_join

Edit: 编辑:

Ah it is windows platform(I failed to notice that before), So you need to use, 啊它是Windows平台(之前我没注意到),所以你需要使用,

WaitForMultipleObjects WaitForMultipleObjects的

What you will likely want to do is create the four threads and then call WaitForSingleObject on the four handles returned, in order. 您可能想要做的是创建四个线程,然后按顺序在返回的四个句柄上调用WaitForSingleObject Just make sure the four threads exit with a call to ExitThread . 只需确保四个线程通过调用ExitThread退出。

EDIT: 编辑:

Or, as pointed out in Hasturkun's answer, use WaitForMultipleObjects ... that would be smart. 或者,正如Hasturkun的回答所指出的,使用WaitForMultipleObjects ......这很聪明。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM