home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / os2sdk / os2sdk12 / suspend / suspend.c next >
Encoding:
C/C++ Source or Header  |  1989-11-20  |  2.1 KB  |  80 lines

  1. /*
  2.  * Example of DosSuspendThread/DosResumeThread usage.
  3.  *
  4.  * DosSuspendThread can be used to ensure mutual exclusion when a thread
  5.  * knows by number all the other threads which might try to access the
  6.  * shared resource.
  7.  * 
  8.  * In this example the main thread can call printf() freely because it
  9.  * knows that the only other thread has been suspended, so the main
  10.  * thread will not be interrupted, and because it knows that the
  11.  * subthread must have been suspended while outside of a critical
  12.  * section, and so the main thread will not be interrupting the
  13.  * subthread's call to vio.
  14.  * 
  15.  * Any thread may suspend any other thread in its process, including the
  16.  * main thread and itself.  If a thread suspends all the threads in a
  17.  * process, including itself, then deadlock will result, and the process
  18.  * will have to be killed externally.
  19.  *
  20.  * Note that there are three methods for managing critical sections
  21.  * amongst threads in a process:
  22.  *
  23.  *    1. Semaphores - this is almost always the right solution
  24.  *    2. DosEnterCritSec
  25.  *    3. DosSuspendThread
  26.  *
  27.  * compile as: cl -Gs -AL -G2 -Lp suspend.c
  28.  *
  29.  * Created by Microsoft Corp. 1986
  30.  */
  31.  
  32. #define INCL_DOSPROCESS
  33. #define INCL_SUB
  34.  
  35. #include <os2def.h>
  36. #include <bse.h>
  37. #include "stdio.h"
  38. #include "malloc.h"
  39. #define STACK_SIZE    1024
  40.  
  41. extern void f_thread(void);
  42. int flag;
  43.  
  44. void main()
  45. {
  46.     char *stkptr;
  47.     TID thread_id;
  48.     register int i;
  49.     
  50.     /* obtain pointer to the END of a block of memory */
  51.     stkptr = (char *)malloc(STACK_SIZE) + STACK_SIZE - 1;
  52.     
  53.     /* create another thread */
  54.     DosCreateThread(f_thread, &thread_id, stkptr);
  55.     
  56.     for(i = 0; i < 20; i++) {
  57.         DosSuspendThread(thread_id);    /* suspend the subthread */
  58.     
  59.         printf("the main thread has suspended thread %u\n", thread_id);
  60.         DosSleep(3000L);
  61.     
  62.         /* resume the subthread */
  63.         printf("now resuming the suspended thread\n");
  64.         DosResumeThread(thread_id);
  65.  
  66.         DosSleep(3000L);
  67.     }
  68.     DosExit(EXIT_PROCESS, 0);       /* exit all threads */
  69. }
  70.  
  71. void f_thread()
  72. {
  73.     while (1) {
  74.         DosEnterCritSec();
  75.         VioWrtTTY("subthread running\r\n", 19, 0);
  76.         DosExitCritSec();
  77.         DosSleep(300L);
  78.     }
  79. }
  80.