简体   繁体   中英

Creating array of threads on Windows

I'm trying to create an array of threads. In Linux, I did it this like:

pthread_t thr[MAXCONNECTIONS];

On Windows, I don't find any replacement for this. 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. You can then pass a HANDLE to various functions to do things on the thread.

WaitForSingleObject(threads[2], INFINITE );

suppose you want to create 10 threads

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 ). This will work with the same code on both Linux and Windows.

You could also use an array of c++11 std::thread 's, which is also portable. Im not sure, but I understand that std::thread isnt complete yet for Windows, so you would probably be better off with Boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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