简体   繁体   English

在Windows上创建线程数组

[英]Creating array of threads on Windows

I'm trying to create an array of threads. 我正在尝试创建一个线程数组。 In Linux, I did it this like: 在Linux中,我这样做:

pthread_t thr[MAXCONNECTIONS];

On Windows, I don't find any replacement for this. 在Windows上,我找不到任何替代品。 Is there anyway to create an array or something that replaces this? 反正有没有创建一个替换它的数组?

HANDLE threads[ThreadCount];

for (int i=0; i < ThreadCount; ++i)
{
   threads[i] = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, NULL, 0, &threadID );
}

I've left out some stuff but you get the jist. 我遗漏了一些东西,但你得到了这个问题。 You have an array of HANDLE's instead of physical threads. 你有一个HANDLE的数组而不是物理线程。 You can then pass a HANDLE to various functions to do things on the thread. 然后,您可以将HANDLE传递给各种函数以在线程上执行操作。

WaitForSingleObject(threads[2], INFINITE );

suppose you want to create 10 threads 假设您要创建10个线程

include this: 包括这个:

#include <Windows.h>
#include <process.h>

thread function look like this: 线程函数看起来像这样:

DWORD WINAPI thread_1(LPVOID lpParam){ /* do something */; return 0; }

array and thread creation: 数组和线程创建:

HANDLE thr[10];
thr[0] = CreateThread(NULL, 0, thread_1, NULL, NULL, NULL);
... etc for 1..9
WaitForMultipleObjects(10, thr, TRUE, INFINITE);

If you have the possibility to use c++ , a more portable solution would be to use an array of Boost threads (link to Boost ). 如果你有可能使用c++ ,一个更便携的解决方案是使用一个Boost线程数组(链接到Boost )。 This will work with the same code on both Linux and Windows. 这将在Linux和Windows上使用相同的代码。

You could also use an array of c++11 std::thread 's, which is also portable. 你也可以使用c++11 std::thread的数组,它也是可移植的。 Im not sure, but I understand that std::thread isnt complete yet for Windows, so you would probably be better off with Boost. 我不确定,但我明白std :: thread还没有完成Windows,所以你可能会更好的使用Boost。

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

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