Advertisement
EBobkunov

ex2 w5 3

Oct 8th, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <string.h>
  5.  
  6. #define MAX_MESSAGE_LENGTH 256
  7.  
  8. // Define the struct Thread
  9. struct Thread {
  10.     pthread_t id;
  11.     int i;
  12.     char message[MAX_MESSAGE_LENGTH];
  13. };
  14.  
  15. // Mutex for synchronization
  16. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  17. int current_thread_index = 0; // Index of the thread that should execute next
  18.  
  19. // Function to be executed by each thread
  20. void* thread_function(void* arg) {
  21.     struct Thread* thread_data = (struct Thread*)arg;
  22.  
  23.     // Create the message
  24.     snprintf(thread_data->message, MAX_MESSAGE_LENGTH, "Hello from thread %d", thread_data->i);
  25.  
  26.     // Synchronize thread execution
  27.     pthread_mutex_lock(&mutex);
  28.  
  29.     // Ensure that the current thread is the one that should execute next
  30.     while (thread_data->i != current_thread_index) {
  31.         pthread_mutex_unlock(&mutex);
  32.         pthread_mutex_lock(&mutex);
  33.     }
  34.  
  35.     // Output the ID and message
  36.     printf("Thread %d: %s\n", thread_data->i, thread_data->message);
  37.  
  38.     // Update the current_thread_index
  39.     current_thread_index++;
  40.  
  41.     pthread_mutex_unlock(&mutex);
  42.  
  43.     return NULL;
  44. }
  45.  
  46. int main(int argc, char* argv[]) {
  47.     if (argc != 2) {
  48.         printf("Usage: %s <number_of_threads>\n", argv[0]);
  49.         return 1;
  50.     }
  51.  
  52.     int n = atoi(argv[1]);
  53.  
  54.     if (n <= 0) {
  55.         printf("Please provide a positive number of threads.\n");
  56.         return 1;
  57.     }
  58.  
  59.     struct Thread threads[n];
  60.  
  61.     for (int i = 0; i < n; i++) {
  62.         threads[i].i = i;
  63.         printf("Thread %d is created\n", i);
  64.  
  65.         if (pthread_create(&threads[i].id, NULL, thread_function, &threads[i]) != 0) {
  66.             perror("pthread_create");
  67.             return 1;
  68.         }
  69.     }
  70.  
  71.     // Wait for all threads to finish
  72.     for (int i = 0; i < n; i++) {
  73.         pthread_join(threads[i].id, NULL);
  74.     }
  75.  
  76.     return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement