Share Your Own Code Samples With the World

Moderators: g3nuin3, SpeedWing, WhiteHat, mezzo


Postby L. Spiro » Mon Jan 08, 2007 10:57 am

Code: Select all
VOID MainThread() {

    // Create a random parameter.
    DWORD dwParm = Random( 90 );
    // Create the thread with this parameter.  We write “SecondThread” ourselves.
    HANDLE hThread = CreateThread( "SecondThread", dwParm );

    // It may have failed!
    if ( !hThread ) {
        PrintF( "Creating the second thread failed." );

    // It succeeded!
    PrintF( "Second thread created with parameter %u.", dwParm );

    // The second thread is active while this one is active.
    // Let’s demonstrate this by holding this thread in a loop for one whole second.
    //  During this second, the other thread should also get its run, printing a
    //  line of text somewhere in the middle of all the text printed in our loop.
    DWORD dwTime = Time();
    DWORD dwCounter = 0;
    while ( Time() - dwTime < 1000 ) {
        if ( dwCounter++ % 100000 == 0 ) {
            PrintF( "\tIn loop, counter is %u.  Time left: %u.",
                dwCounter, 1000 - (Time() - dwTime) );
    PrintF( "Done." );

    // If CreateThread() is successful, the valid handle must be closed!
    CloseHandle( hThread );

// And this is the function called by CreateThread() above.
// dwParm is the parameter passed in CreateThread() and can be whatever we want it to
//  be—a number, a pointer, whatever.  If more parameters are needed than just one,
//  organize them into a structure and pass a pointer to the structure to
//  CreateThread() (the pointer will be cast to a DWORD, then you can cast it back
//  inside your second thread).
DWORD SecondThread( DWORD dwParm ) {
    // All we need to do for this example is print the parameter passed to us.
    PrintF( "From Second Thread: %u.", dwParm );

This demonstrates how to create a second thread.
In my example, the first thread will execute longer than the second thread however this is not required.

In any case, whethere it ends before or after the second thread, the first thread should call CloseHandle() on the returned second thread handle (this does not stop the second thread; it just releases resources).

This example will have both threads printing at the same time, so you can see how they execute together.

Code: Select all
VOID On_HK_0( DWORD dwP1, DWORD dwP2 ) {

You can use this concept to run the SearchDir() function posted here, but this is for advanced users, since you have to figure out how to deal with the fact that CreateThread() allows passing 1 parameter while SearchDir() takes 3.
Hint: pointers to structures.

L. Spiro
User avatar
L. Spiro
L. Spiro
Posts: 3126
Joined: Mon Jul 17, 2006 10:14 pm
Location: Tokyo, Japan

Return to Code Submissions

Who is online

Users browsing this forum: No registered users and 1 guest