Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- 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.
- Here's an example of a basic scheduler that allows each thread to execute a fixed number of times before switching:
- ```c
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/mman.h>
- #include <setjmp.h>
- #define MAX_THREADS 10
- #define STACK_SIZE (1 << 20)
- int NUM_ALIVE_THREADS = 1;
- int THREAD_COMPLETED = 0;
- int current_thread = 0;
- int QUANTUM = 10; // Define the number of iterations each thread gets before switching
- mythread_t* threads[MAX_THREADS];
- void schedule() {
- int start_thread = current_thread;
- int iterations = 0;
- 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) {
- longjmp(threads[current_thread]->env, 1);
- }
- iterations++;
- } while (iterations < QUANTUM && 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 your code remains the same)
- ```
- 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