Advertisement
stream13

Simple multithreading example befor bed )

Feb 18th, 2013
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <process.h>         // needed for _beginthread()
  4.  
  5. struct sourcendest{
  6.     char * source;
  7.     char * destination;
  8. };
  9. void testfunc( void * arg );   // function prototype
  10. void testfunc2( void * sd1 );
  11.  
  12.  
  13. int main(){
  14.     // Our program's first thread starts in the main() function.
  15.  
  16.     printf( "Now in the main() function.\n" );
  17.  
  18.     // Let's now create our second thread and ask it to start
  19.     // in the testfunc() function.
  20.  
  21.     _beginthread( testfunc, 0, (void*)12 );
  22.  
  23.     // From here on there are two separate threads executing
  24.     // our one program.
  25.  
  26.     // This main thread can call the testfunc() function if it wants to.
  27.  
  28.     testfunc( (void*)-5 );
  29.  
  30.     char c1[50] = "All heil Megatron!\0";
  31.     char c2[50] = "Black patryvan is coming for you!\0";
  32.     char c3[50] = "\0";
  33.     char c4[50] = "\0";
  34.     sourcendest * sd01, * sd02;
  35.     sd01 = new sourcendest;
  36.     sd02 = new sourcendest;
  37.     sd01->source = c1;
  38.     sd02->source = c2;
  39.     sd01->destination = c3;
  40.     sd02->destination = c4;
  41.     printf("c1 = '%s'\nc2 = '%s'\nc3 = '%s'\nc4 = '%s'\n\n", c1,c2,c3,c4);
  42.     testfunc2(sd01);
  43.     _beginthread( testfunc2, 0, (void*)sd02 );
  44.     Sleep( 1000 );
  45.     printf("c1 = '%s'\nc2 = '%s'\nc3 = '%s'\nc4 = '%s'\n\n", c1,c2,c3,c4);
  46.  
  47. }
  48.  
  49. void testfunc( void * arg){
  50.     printf( "The testfunc() function was passed %d\n", (INT_PTR)arg ) ;
  51. }
  52. void testfunc2( void * sd1 ){
  53.     sourcendest * lsd1 = (sourcendest *) sd1;
  54.     unsigned int i = 0;
  55.     for (; lsd1->source[i] > 0; ++i){
  56.         lsd1->destination[i]=lsd1->source[i];
  57.     }
  58.     lsd1->destination[i]=0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement