Advertisement
EBobkunov

ex2 w5 2

Oct 8th, 2023 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 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. // Function to be executed by each thread
  16. void* thread_function(void* arg) {
  17.     struct Thread* thread_data = (struct Thread*)arg;
  18.    
  19.     // Create the message
  20.     snprintf(thread_data->message, MAX_MESSAGE_LENGTH, "Hello from thread %d", thread_data->i);
  21.    
  22.     // Output the ID and message
  23.     printf("Thread %d: %s\n", thread_data->i, thread_data->message);
  24.    
  25.     return NULL;
  26. }
  27.  
  28. int main(int argc, char* argv[]) {
  29.     if (argc != 2) {
  30.         printf("Usage: %s <number_of_threads>\n", argv[0]);
  31.         return 1;
  32.     }
  33.  
  34.     int n = atoi(argv[1]);
  35.  
  36.     if (n <= 0) {
  37.         printf("Please provide a positive number of threads.\n");
  38.         return 1;
  39.     }
  40.  
  41.     struct Thread threads[n];
  42.  
  43.     for (int i = 0; i < n; i++) {
  44.         threads[i].i = i;
  45.         printf("Thread %d is created\n", i);
  46.  
  47.         if (pthread_create(&threads[i].id, NULL, thread_function, &threads[i]) != 0) {
  48.             perror("pthread_create");
  49.             return 1;
  50.         }
  51.     }
  52.  
  53.     // Wait for all threads to finish
  54.     for (int i = 0; i < n; i++) {
  55.         pthread_join(threads[i].id, NULL);
  56.     }
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement