Skip navigation

A simple example that shows how to create a thread in C++ on Win32 platform

    #include <Windows.h>
    #include <stdio.h>
    
    struct Point
    {
      float x,y,z ;
    } ;
    
    DWORD WINAPI threadStartPoint( LPVOID data )
    {
      Sleep( 1000 ) ;
      Point *p = (Point*)data ;
      printf( "%f %f %f\n", p->x, p->y, p->z ) ;
      puts( "Thread job done" ) ;
      return 0 ;
    }
    
    // From main
    int main()
    {
      DWORD threadId ;
      Point p ;
      p.x=2, p.y=3, p.z=4 ;
      HANDLE handle = CreateThread( 0, 0, 
        threadStartPoint,
        (LPVOID)&p,
        0,
        &threadId
      ) ;
    
      if( !handle )
      {
        // Thread creation failed
        puts( "start fail\n" );
      }
      else
      {
        printf( "started on threadid=%d\n", threadId ) ;
      }
    
      WaitForSingleObject( handle, 2000 ) ; // wait up to 2000 ms for the other thread to complete before moving on
    
      puts( "main thread Exiting.." ) ;
      //system( "pause" ) ;
    }

Advertisements

One Comment

  1. I just couldn’t go away your web site prior to suggesting that I
    extremely loved the standard information a person provide on your visitors?

    Is going to be back frequently in order to inspect new posts


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: