fork(3) download
  1. #include <pthread.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5.  
  6.  
  7. #define PID_MIN 0
  8. #define PID_MAX 3
  9.  
  10. #define NUM_THREADS 100
  11. #define ITERATIONS 10
  12. #define SLEEP 5
  13.  
  14.  
  15.  
  16.  
  17. int S;
  18.  
  19. /* mutex lock for accessing pid_map */
  20. pthread_mutex_t mutex;
  21.  
  22. int pid_map[PID_MAX-PID_MIN+1];
  23. int thread_counter =0;
  24.  
  25.  
  26. int allocate_map(void);
  27. int allocate_pid(void);
  28. void release_pid(int pid);
  29.  
  30.  
  31. // Allocates the pid map.
  32.  
  33. int allocate_map(void)
  34. {
  35. /*initilize to zero explicitly just to make sure*/
  36. int i;
  37. for (i =0;i<PID_MAX-PID_MIN+1;i++)
  38. {
  39. pid_map[i] = 0;
  40. S++;
  41.  
  42. }
  43. printf("map allocated!S=%d\n",S);
  44. return 1;
  45. }
  46.  
  47. /**
  48.  * Allocates a pid
  49.  */
  50. int allocate_pid(void)
  51. {
  52. int next_pid;
  53. int i;
  54. while (S<=0)
  55. {}
  56.  
  57. pthread_mutex_lock(&mutex);
  58. S--;
  59. for (i =0;i<PID_MAX-PID_MIN;i++)
  60. {
  61. if (pid_map[i] == 0)
  62. {
  63. pid_map[i] = 1;
  64. next_pid=i;
  65. pthread_mutex_unlock(&mutex);
  66. return next_pid+PID_MIN;
  67.  
  68.  
  69.  
  70. }
  71. }
  72.  
  73.  
  74. }
  75. /**
  76.  * Releases a pid
  77.  */
  78. void release_pid(int pid)
  79. {
  80. pid = pid-PID_MIN;
  81. pid_map[pid] = 0;
  82. S++;
  83. }
  84.  
  85. void *do_something(void *threadid)
  86. {
  87. int my_pid;
  88. long thread_id;
  89. int i;
  90. double r;
  91. thread_id= (long)threadid;
  92.  
  93. for (i=0;i<ITERATIONS;i++)
  94. {
  95. r = rand()%50; // 0-50
  96. r=r/10;
  97. //r=0.1;
  98. //printf("thread %d trying to allocate PID..., S=%d\n",thread_id,S);
  99. my_pid=allocate_pid();
  100.  
  101. printf("Thread number %d got PID %d S=%d\n", thread_id, my_pid,S);
  102. sleep(r);
  103. release_pid(my_pid);
  104. printf("Thread number %d released PID %d S=%d \n", thread_id, my_pid,S);
  105. }
  106. thread_counter--;
  107. pthread_exit(NULL);
  108. }
  109.  
  110.  
  111. void main()
  112. {
  113. int i,rc;
  114. time_t t;
  115. pthread_t tid[NUM_THREADS];
  116. srand((unsigned) time(&t));
  117. allocate_map();
  118. for (i =0;i<10;i++)
  119. {
  120. //printf("In main: creating thread %d S=%d\n", i,S);
  121. thread_counter++;
  122. rc=pthread_create(&tid[i], NULL, do_something, (void *)i);
  123.  
  124. }
  125. while (thread_counter >0)
  126. {
  127. sleep(1);
  128. }
  129. printf("DONE!\n");
  130. }
  131.  
  132.  
  133.  
  134.  
Time limit exceeded #stdin #stdout 5s 84224KB
stdin
Standard input is empty
stdout
Standard output is empty