1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <string>
#include <process.h>
#include <Windows.h>
struct Data // lazy struct
{
Data(int id_, const std::string& title_)
: id(id_), title(title_) { }
int id;
std::string title;
};
unsigned __stdcall show_thread_proc(void *param)
{
Data* data = reinterpret_cast<Data*>(param);
std::string message = std::to_string(data->id);
MessageBoxA(NULL, message.c_str(), data->title.c_str(), MB_OK | MB_ICONEXCLAMATION);
delete data;
return 0;
}
void doThreads()
{
const unsigned num_threads = 10;
HANDLE hthreads[num_threads] = {0};
for ( unsigned i=0; i<num_threads; ++i ) {
Data* data = new Data(i, "Hello world!");
hthreads[i] = (HANDLE)_beginthreadex(0, 0, show_thread_proc,
reinterpret_cast<void*>(data), 0, 0) ;
// do not delete data -- that's up to thread
}
// Here, TRUE means wait for all threads, rather than just any
// single thread, to signal
WaitForMultipleObjects(num_threads, hthreads, TRUE, INFINITE);
for ( unsigned i=0; i<num_threads; ++i ) {
CloseHandle(hthreads[num_threads]);
}
}
int main()
{
doThreads() ;
MessageBoxA(NULL, "We're done here!", "Finished", 0) ;
}
|