STEPAN_KODER

Untitled

Sep 27th, 2023
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. To synchronize access to the standard output without using `pthread_mutex`, you can use atomic operations. In this case, we can use `__sync_lock_test_and_set` and `__sync_synchronize` for a simple lock.
  2.  
  3. Here's the modified code:
  4.  
  5. ```c
  6. // ... (previous code remains the same)
  7.  
  8. volatile int print_lock = 0;
  9.  
  10. void *work(void *arg) {
  11. for(int i = 0; i < 100; i++){
  12. while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
  13. printf("hello world %d\n", i);
  14. __sync_synchronize(); // Ensure the printf completes before releasing lock
  15. print_lock = 0; // Release lock
  16. }
  17. return NULL;
  18. }
  19.  
  20. void *work2(void *arg) {
  21. for(int i = 0; i < 10; i++){
  22. while (__sync_lock_test_and_set(&print_lock, 1)); // Attempt to acquire lock
  23. printf("ADS %d\n", i);
  24. __sync_synchronize(); // Ensure the printf completes before releasing lock
  25. print_lock = 0; // Release lock
  26. }
  27. return (void *) 10;
  28. }
  29.  
  30. int main(int argc, char *argv[]) {
  31. // ... (previous code remains the same)
  32.  
  33. mythread_t t, t2;
  34. mythread_create(&t, work, NULL);
  35. mythread_create(&t2, work2, NULL);
  36. mythread_detach(&t);
  37. int *res = malloc(sizeof(int));
  38. mythread_join(&t2, (void **) res);
  39. mythread_exit();
  40. return 0;
  41. }
  42. ```
  43.  
  44. In this code, we use `__sync_lock_test_and_set` to attempt to acquire the lock. If the lock is already held (`print_lock == 1`), the thread will spin in a loop until it can acquire the lock. After printing, we use `__sync_synchronize` to ensure that the `printf` completes before releasing the lock.
  45.  
  46. Please try running this code and let me know if it resolves the issue.
Advertisement
Add Comment
Please, Sign In to add comment