First thing you need to realize:
for (int i = 0; i < numRuns; i++)
{
_beginthread( myThread, 0, (void *) (array1) );
_beginthread( myThread2, 0, (void *) (array2) );
}
The calls to _beginthread
return immediately. They don't wait for the threads to finish, or even to start. It just queues up the thread in the OS's scheduler and returns.
However, the code above is the end of the main()
function. I very much doubt that under a Release build your threads will even have initialized before your whole program exits. You need to build a mechanism by which your main thread will wait for the worker threads to finish their work before your program shuts down. Doing this is way beyond the scope of an SO post, but look in to CreateEvent() and WaitForMultipleObjects().
Next thing you need to understand is the lifetime and ownership semantics of the stuff you send to the threads. You are passing pointers to arrays which are automatic variables scoped in main()
:
int array1[1000000];
int array2[1000000];
As soon as the scope in which these arrays are declared (here, main()
) exits, the variables cease to exist. It is rarely, if ever, correct to pass a pointer to a locally-scoped variable to a worker thread -- never correct if the local scope exits before the thread finishes.
Dynamically allocating those arrays and then transferring ownership of them to the worker threads will fix that problem here. When doing this, please be careful when managing the ownership semantics of these objects/arrays.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…