Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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:
- ```c
- // ... (previous code remains the same)
- void schedule() {
- int start_thread = current_thread;
- do {
- current_thread = (current_thread + 1) % NUM_ALIVE_THREADS;
- if (threads[current_thread] != NULL && threads[current_thread]->joined && threads[current_thread]->active && !threads[current_thread]->completed) {
- return;
- }
- } while (current_thread != start_thread);
- }
- void* routine_wrapper(void *arg){
- mythread_t* t = (mythread_t *)arg;
- if (setjmp(t->env) == 0) {
- t->res = t->start_routine(t->arg);
- t->completed = 1;
- schedule();
- } else {
- if (__sync_fetch_and_add(&THREAD_COMPLETED, 1) == NUM_ALIVE_THREADS - 1) {
- __sync_synchronize();
- schedule();
- } else {
- pause();
- }
- }
- }
- // ... (rest of the code remains the same)
- ```
- 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.
- 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