Advertisement
STEPAN_KODER

Untitled

Sep 27th, 2023
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. In your current design, threads are scheduled in a round-robin manner. This means each thread gets a turn to run in order, but there's no guarantee on how many iterations of the loop each thread gets before the next thread is scheduled. This can lead to the behavior you're observing where "hello world 14" may not be the last output.
  2.  
  3. If you want to achieve a more deterministic behavior where each thread gets to execute a certain number of times before switching, you'll need to implement a more sophisticated scheduler.
  4.  
  5. Here's an example of a basic scheduler that allows each thread to execute a fixed number of times before switching:
  6.  
  7. ```c
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <sys/mman.h>
  12. #include <setjmp.h>
  13.  
  14. #define MAX_THREADS 10
  15. #define STACK_SIZE (1 << 20)
  16.  
  17. int NUM_ALIVE_THREADS = 1;
  18. int THREAD_COMPLETED = 0;
  19. int current_thread = 0;
  20. int QUANTUM = 10; // Define the number of iterations each thread gets before switching
  21.  
  22. mythread_t* threads[MAX_THREADS];
  23.  
  24. void schedule() {
  25. int start_thread = current_thread;
  26. int iterations = 0;
  27.  
  28. do {
  29. current_thread = (current_thread + 1) % NUM_ALIVE_THREADS;
  30. if (threads[current_thread] != NULL && threads[current_thread]->joined && threads[current_thread]->active && !threads[current_thread]->completed) {
  31. longjmp(threads[current_thread]->env, 1);
  32. }
  33.  
  34. iterations++;
  35. } while (iterations < QUANTUM && current_thread != start_thread);
  36. }
  37.  
  38. void* routine_wrapper(void *arg) {
  39. mythread_t* t = (mythread_t *)arg;
  40. if (setjmp(t->env) == 0) {
  41. t->res = t->start_routine(t->arg);
  42. t->completed = 1;
  43. schedule();
  44. } else {
  45. if (__sync_fetch_and_add(&THREAD_COMPLETED, 1) == NUM_ALIVE_THREADS - 1) {
  46. __sync_synchronize();
  47. schedule();
  48. } else {
  49. pause();
  50. }
  51. }
  52. }
  53.  
  54. // ... (rest of your code remains the same)
  55. ```
  56.  
  57. In this example, I've added a `QUANTUM` value which determines how many iterations each thread gets before the scheduler switches to the next thread. You can adjust this value to control the behavior of your threads.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement