Advertisement
EBobkunov

ex2 w5 relife

Oct 9th, 2023
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <string.h>
  5.  
  6. // Define the struct Thread
  7. struct Thread {
  8.     pthread_t id;        // Thread ID
  9.     int i;               // Index of the thread
  10.     char message[256];   // Message
  11. };
  12.  
  13. // Function that each thread will execute
  14. void *thread_function(void *arg) {
  15.     struct Thread *thread_data = (struct Thread *)arg;
  16.     printf("Thread %d is created\n", thread_data->i);
  17.     sprintf(thread_data->message, "Hello from thread %d", thread_data->i);
  18.     printf("Thread %d: %s\n", thread_data->i, thread_data->message);
  19.     pthread_exit(NULL);
  20. }
  21.  
  22. int main(int argc, char *argv[]) {
  23.     if (argc != 2) {
  24.         printf("Usage: %s <number_of_threads>\n", argv[0]);
  25.         return 1;
  26.     }
  27.  
  28.     int n = atoi(argv[1]);
  29.     if (n <= 0) {
  30.         printf("Please provide a positive integer for the number of threads.\n");
  31.         return 1;
  32.     }
  33.  
  34.     struct Thread threads[n]; // Array of Thread structs
  35.  
  36.     for (int i = 0; i < n; i++) {
  37.         threads[i].i = i; // Set the index of the thread
  38.         if (pthread_create(&threads[i].id, NULL, thread_function, &threads[i]) != 0) {
  39.             perror("Thread creation failed");
  40.             return 1;
  41.         }
  42.         // Wait for the thread to finish before creating the next one
  43.         pthread_join(threads[i].id, NULL);
  44.     }
  45.  
  46.     return 0;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement