Advertisement
EBobkunov

ex2 w5

Oct 8th, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4.  
  5. #define MAX_MESSAGE_SIZE 256
  6.  
  7. struct Thread {
  8.     pthread_t id;
  9.     int i;
  10.     char message[MAX_MESSAGE_SIZE];
  11. };
  12.  
  13. void* thread_function(void* arg) {
  14.     struct Thread* thread_data = (struct Thread*)arg;
  15.  
  16.     printf("Thread %d prints message: %s\n", thread_data->i, thread_data->message);
  17.    
  18.     // Exit the thread
  19.     pthread_exit(NULL);
  20. }
  21.  
  22. int main(int argc, char* argv[]) {
  23.     if (argc != 2) {
  24.         fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
  25.         return 1;
  26.     }
  27.  
  28.     int n = atoi(argv[1]);
  29.  
  30.     if (n <= 0) {
  31.         fprintf(stderr, "Number of threads must be a positive integer.\n");
  32.         return 1;
  33.     }
  34.  
  35.     struct Thread threads[n];
  36.  
  37.     // Create threads
  38.     for (int i = 0; i < n; i++) {
  39.         threads[i].i = i + 1;
  40.         snprintf(threads[i].message, sizeof(threads[i].message), "Hello from thread %d", threads[i].i);
  41.        
  42.         printf("Thread %d is created\n", threads[i].i);
  43.  
  44.         if (pthread_create(&threads[i].id, NULL, thread_function, (void*)&threads[i]) != 0) {
  45.             perror("pthread_create");
  46.             return 1;
  47.         }
  48.     }
  49.  
  50.     // Wait for threads to finish
  51.     for (int i = 0; i < n; i++) {
  52.         pthread_join(threads[i].id, NULL);
  53.     }
  54.  
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement