By plaving around with the code, a new issue has arrised,
see the code
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include "MyApp.h"
void MyApp::print()
{
for (int i = loopStart; i <= loopEnd; ++i)
{
if (i % dispFrequency == 0)
{
printf( "%d: i = %d\n", threadName, i );
}
}
printf( "%d thread terminating\n", threadName );
}
void MyApp::setName(int &t)
{
#ifdef WITH_SYNCHRONIZATION
EnterCriticalSection( &m_CriticalSection );
#endif
threadName = t;
#ifdef WITH_SYNCHRONIZATION
LeaveCriticalSection( &m_CriticalSection );
#endif
}
int main()
{
HANDLE threads[CPU];
unsigned uiThread1ID[CPU];
for(int i = 0; i < CPU; i++)
{
MyApp *o1 = new MyApp(0, 1000000, 20000);
o1->setName(i); //critical section
threads[i] = (HANDLE)_beginthreadex( NULL, // security
0, // stack size
MyApp::ThreadStaticEntryPoint,
o1, // arg list
0,
&uiThread1ID[i] );
if ( threads[i] == 0 )
printf("Failed to create thread 1\n");
//DWORD dwExitCode;
//GetExitCodeThread( threads[i], &dwExitCode ); // should be STILL_ACTIVE = 0x00000103 = 259
//printf( "initial thread %d exit code = %u\n", i, dwExitCode );
}
WaitForMultipleObjects(CPU, threads, true, INFINITE);
printf("This pain has ended!\n");
}
|
now when I move o1 pointer declaration outside the for loop, exmp in line 37, then there is no interleaving at all, it is executing only the last loop, cor CPU = 5, I get only the last loop i = 4.
But, with the pointe as it is, it works fine, however, creating so many pointers in the loop, I find it inefficient isn't it ?
Furthermore, with the code as it is, when I add the following lines (in the for loop):
delete o1;
o1 = NULL;
My application is behaving strange, and in Win 7 is reporting an error. Why is that? really strange.
Oh by the way, how does one close HANDLEs in this fashion? In one by one, manual thread creation I used to simply call this
CloseHandle( hth1 );
Or should I still call this in a seperate loop or there is a better way todo so?
thanx