Advertisement
STEPAN_KODER

Untitled

Sep 27th, 2023
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. I understand that you want to achieve thread switching without using `mythread_yield()` explicitly. To do this, we can implement a simple round-robin scheduler that automatically switches between threads. Below is the modified code:
  2.  
  3. ```c
  4. // ... (previous code remains the same)
  5.  
  6. void schedule() {
  7. int start_thread = current_thread;
  8. do {
  9. current_thread = (current_thread + 1) % NUM_ALIVE_THREADS;
  10. if (threads[current_thread] != NULL && threads[current_thread]->joined && threads[current_thread]->active && !threads[current_thread]->completed) {
  11. return;
  12. }
  13. } while (current_thread != start_thread);
  14. }
  15.  
  16. void* routine_wrapper(void *arg){
  17. mythread_t* t = (mythread_t *)arg;
  18. if (setjmp(t->env) == 0) {
  19. t->res = t->start_routine(t->arg);
  20. t->completed = 1;
  21. schedule();
  22. } else {
  23. if (__sync_fetch_and_add(&THREAD_COMPLETED, 1) == NUM_ALIVE_THREADS - 1) {
  24. __sync_synchronize();
  25. schedule();
  26. } else {
  27. pause();
  28. }
  29. }
  30. }
  31.  
  32. // ... (rest of the code remains the same)
  33. ```
  34.  
  35. In this code, I've modified the `routine_wrapper` function. Now, after a thread finishes its work and is about to exit, it will call `schedule()` to select the next thread to run. The `schedule` function will loop through the threads to find the next runnable thread.
  36.  
  37. With this modification, you don't need to manually call `mythread_yield()` in your thread functions (`work` and `work2`). The scheduling is handled automatically after a thread completes its execution.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement