Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I apologize for the confusion. It seems like there's an issue in your code. The problem arises because `longjmp` does not return like a normal function, so when it returns in the `routine_wrapper`, it doesn't return to the main loop in the `work` function. Instead, it ends up executing the rest of the loop in `work`.
- To fix this, you can use a different approach. Instead of using `longjmp` to return from `routine_wrapper`, you can directly call `mythread_yield()` to switch to the next thread. Additionally, I'll provide a fix for the print lock.
- Here's the modified code:
- ```c
- // ... (previous code remains the same)
- volatile int print_lock = 0;
- void *work(void *arg) {
- for(int i = 0; i < 100; i++){
- while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
- printf("hello world %d\n", i);
- __sync_synchronize(); // Ensure the printf completes before releasing lock
- print_lock = 0; // Release lock
- mythread_yield(); // Switch to the next thread
- }
- return NULL;
- }
- void *work2(void *arg) {
- for(int i = 0; i < 10; i++){
- while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
- printf("ADS %d\n", i);
- __sync_synchronize(); // Ensure the printf completes before releasing lock
- print_lock = 0; // Release lock
- mythread_yield(); // Switch to the next thread
- }
- return (void *) 10;
- }
- int main(int argc, char *argv[]) {
- mythread_t t, t2;
- mythread_create(&t, work, NULL);
- mythread_create(&t2, work2, NULL);
- mythread_detach(&t);
- int *res = malloc(sizeof(int));
- mythread_join(&t2, (void **) res);
- mythread_exit();
- return 0;
- }
- ```
- In this code, we've replaced `longjmp` with `mythread_yield()` in both `work` and `work2` functions to properly yield to the next thread. Additionally, I've made sure to call `mythread_yield()` after releasing the lock to switch to the next thread.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement