|
|
1.1 root 1: /* 1.1.1.2 ! root 2: * Example of DosSuspendThread/DosResumeThread usage. 1.1 root 3: * 1.1.1.2 ! root 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 1.1 root 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: * 1.1.1.2 ! root 29: * Created by Microsoft Corp. 1986 1.1 root 30: */ 31: 1.1.1.2 ! root 32: #define INCL_DOSPROCESS ! 33: #define INCL_SUB ! 34: ! 35: #include <os2def.h> ! 36: #include <bse.h> 1.1 root 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; 1.1.1.2 ! root 47: TID thread_id; 1.1 root 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 */ 1.1.1.2 ! root 54: DosCreateThread(f_thread, &thread_id, stkptr); 1.1 root 55: 56: for(i = 0; i < 20; i++) { 1.1.1.2 ! root 57: DosSuspendThread(thread_id); /* suspend the subthread */ 1.1 root 58: 59: printf("the main thread has suspended thread %u\n", thread_id); 1.1.1.2 ! root 60: DosSleep(3000L); 1.1 root 61: 62: /* resume the subthread */ 63: printf("now resuming the suspended thread\n"); 1.1.1.2 ! root 64: DosResumeThread(thread_id); 1.1 root 65: 1.1.1.2 ! root 66: DosSleep(3000L); 1.1 root 67: } 1.1.1.2 ! root 68: DosExit(EXIT_PROCESS, 0); /* exit all threads */ 1.1 root 69: } 70: 71: void f_thread() 72: { 73: while (1) { 1.1.1.2 ! root 74: DosEnterCritSec(); ! 75: VioWrtTTy("subthread running\r\n", 19, 0); ! 76: DosExitCritSec(); ! 77: DosSleep(300L); 1.1 root 78: } 79: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.