Advertisement
STEPAN_KODER

Untitled

Sep 27th, 2023
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. Certainly, I've reviewed the code and found a potential issue. The problem lies in how the threads are managed and how they access shared resources. Specifically, the `printf` statements in the `work` and `work2` functions are not synchronized, leading to unexpected outputs.
  2.  
  3. To fix this, we can introduce a mutex to ensure that only one thread can access the standard output at a time. Here's the modified code:
  4.  
  5. ```c
  6. // ... (previous code remains the same)
  7.  
  8. pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER;
  9.  
  10. void *work(void *arg) {
  11. for(int i = 0; i < 100; i++){
  12. pthread_mutex_lock(&print_lock); // Lock before printing
  13. printf("hello world %d\n", i);
  14. pthread_mutex_unlock(&print_lock); // Unlock after printing
  15. }
  16. return NULL;
  17. }
  18.  
  19. void *work2(void *arg) {
  20. for(int i = 0; i < 10; i++){
  21. pthread_mutex_lock(&print_lock); // Lock before printing
  22. printf("ADS %d\n", i);
  23. pthread_mutex_unlock(&print_lock); // Unlock after printing
  24. }
  25. return (void *) 10;
  26. }
  27.  
  28. int main(int argc, char *argv[]) {
  29. // ... (previous code remains the same)
  30. pthread_mutex_init(&print_lock, NULL);
  31.  
  32. mythread_t t, t2;
  33. mythread_create(&t, work, NULL);
  34. mythread_create(&t2, work2, NULL);
  35. mythread_detach(&t);
  36. int *res = malloc(sizeof(int));
  37. mythread_join(&t2, (void **) res);
  38. mythread_exit();
  39. pthread_mutex_destroy(&print_lock);
  40. return 0;
  41. }
  42. ```
  43.  
  44. In this code, I've introduced a `pthread_mutex_t` named `print_lock`. Before printing any message, a thread will lock the mutex, and after printing, it will unlock it. This ensures that only one thread is printing at a time, preventing output interference.
  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
Advertisement