Advertisement
STEPAN_KODER

Untitled

Sep 27th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. 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`.
  2.  
  3. 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.
  4.  
  5. Here's the modified code:
  6.  
  7. ```c
  8. // ... (previous code remains the same)
  9.  
  10. volatile int print_lock = 0;
  11.  
  12. void *work(void *arg) {
  13. for(int i = 0; i < 100; i++){
  14. while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
  15. printf("hello world %d\n", i);
  16. __sync_synchronize(); // Ensure the printf completes before releasing lock
  17. print_lock = 0; // Release lock
  18. mythread_yield(); // Switch to the next thread
  19. }
  20. return NULL;
  21. }
  22.  
  23. void *work2(void *arg) {
  24. for(int i = 0; i < 10; i++){
  25. while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
  26. printf("ADS %d\n", i);
  27. __sync_synchronize(); // Ensure the printf completes before releasing lock
  28. print_lock = 0; // Release lock
  29. mythread_yield(); // Switch to the next thread
  30. }
  31. return (void *) 10;
  32. }
  33.  
  34. int main(int argc, char *argv[]) {
  35. mythread_t t, t2;
  36. mythread_create(&t, work, NULL);
  37. mythread_create(&t2, work2, NULL);
  38. mythread_detach(&t);
  39. int *res = malloc(sizeof(int));
  40. mythread_join(&t2, (void **) res);
  41. mythread_exit();
  42. return 0;
  43. }
  44. ```
  45.  
  46. 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