home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 10 / 10.iso / l / l430 / 1.ddi / CHAP5.ZIP / SEMTEST.C < prev    next >
Encoding:
C/C++ Source or Header  |  1992-06-13  |  2.3 KB  |  81 lines

  1. /*
  2.     SEMTEST.C -- Using WaitEvent and PostEvent semaphores
  3.  
  4.     From Chapter 5 of "Undocumented Windows" (Addison-Wesley 1992)
  5.     by Andrew Schulman, Dave Maxey and Matt Pietrek
  6.  
  7.     Build using: WINIOBC SEMTEST HANDLES (for Borland C++ v3.00)
  8.                  WINIOMS SEMTEST HANDLES (for Microsoft C/SDK)
  9.                      
  10.     Changed from version in book:  the task doing WaitEvent()
  11.     shouldn't yield.  Unfortunately, the puts() function in WINIO
  12.     has to yield.  So, don't print anything.
  13. */
  14.  
  15. #include <windows.h>
  16. #include <stdlib.h>
  17. #include <time.h>
  18. #include "winio.h"
  19. #include "handles.h"
  20.  
  21. /* from WINEXP.H -- "scheduler things that the world knows not" */
  22. BOOL far PASCAL WaitEvent(HANDLE);
  23. BOOL far PASCAL PostEvent(HANDLE);
  24.  
  25. void waste_time()   // waste a random amount of time
  26. {
  27.     static time_t t = 0;
  28.     int i;
  29.     
  30.     if (t == 0)     // one-time initialization
  31.         srand(time(&t));
  32.     
  33.     for (i=rand(); i--; )
  34.         GetVersion();
  35. }
  36.             
  37. main(int argc, char *argv[])
  38. {
  39.     extern HANDLE __hPrevInst;  // in ARGCARGV.C
  40.     HANDLE hSecondInst, hSecondTask;
  41.     int i;
  42.         
  43.     winio_about("SEMTEST"
  44.         "\nUsing WaitEvent and PostEvent semaphores"
  45.         "\n\nFrom Chapter 5 of"
  46.         "\n\"Undocumented Windows\" (Addison-Wesley, 1992)"
  47.         "\nby Andrew Schulman, David Maxey and Matt Pietrek"
  48.         );
  49.     
  50.     if (! __hPrevInst)
  51.     {
  52.         winio_settitle(winio_current(), "SEMTEST - First Task");
  53.         if ((hSecondInst = WinExec(argv[0], SW_NORMAL)) <= 32) // fork
  54.             fail("Could not EXEC second task");
  55.         hSecondTask = hTask_from_hInstance(hSecondInst);
  56.         for (i=10; i--; )
  57.         {
  58.             waste_time();
  59.             puts("I'm about to wake second task");
  60.             PostEvent(hSecondTask);
  61.             puts("I woke second task");
  62.         }
  63.     }
  64.     else    // I must be the second task
  65.     {
  66.         winio_settitle(winio_current(), "SEMTEST - Second Task");
  67.         for (i=10; i--; )
  68.         {
  69.             // yielding in here causes problems
  70.  
  71.             waste_time();
  72.             // puts("I'm about to wait");
  73.             WaitEvent(0);
  74.             // puts("Thanks, I needed that");
  75.         }
  76.     }
  77.     puts("done");
  78.     return 0;
  79. }
  80.  
  81.