fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <time.h>
  5.  
  6. #define MAX_SIZE 100 // Max size of the arrays
  7.  
  8. // Declare the arrays A, B, and C globally
  9. int A[MAX_SIZE], B[MAX_SIZE], C[MAX_SIZE];
  10. int N; // Size of the arrays
  11.  
  12. // Thread function to compute C[i] = A[i] + B[i]
  13. void *vector_sum(void *arg) {
  14. int index = *(int *)arg; // The thread index is passed as an argument
  15. C[index] = A[index] + B[index];
  16. pthread_exit(NULL);
  17. }
  18.  
  19. int main() {
  20. // Seed the random number generator
  21. srand(time(NULL));
  22.  
  23. // Get the size of the arrays (N)
  24. printf("Enter the size of the arrays (N <= 100): ");
  25. scanf("%d", &N);
  26.  
  27. // Initialize arrays A and B with random values between 0 and 10
  28. for (int i = 0; i < N; i++) {
  29. A[i] = rand() % 11; // Random number between 0 and 10
  30. B[i] = rand() % 11; // Random number between 0 and 10
  31. }
  32.  
  33. // Create an array of threads
  34. pthread_t threads[MAX_SIZE];
  35.  
  36. // Create threads to compute C[i] = A[i] + B[i]
  37. for (int i = 0; i < N; i++) {
  38. int *index = malloc(sizeof(*index));
  39. *index = i;
  40. if (pthread_create(&threads[i], NULL, vector_sum, (void *)index) != 0) {
  41. perror("Error creating thread");
  42. return 1;
  43. }
  44. }
  45.  
  46. // Join the threads to ensure they complete before printing the result
  47. for (int i = 0; i < N; i++) {
  48. pthread_join(threads[i], NULL);
  49. }
  50.  
  51. // Print the arrays A, B, and C
  52. printf("Array A: ");
  53. for (int i = 0; i < N; i++) {
  54. printf("%d ", A[i]);
  55. }
  56. printf("\n");
  57.  
  58. printf("Array B: ");
  59. for (int i = 0; i < N; i++) {
  60. printf("%d ", B[i]);
  61. }
  62. printf("\n");
  63.  
  64. printf("Array C (Sum of A and B): ");
  65. for (int i = 0; i < N; i++) {
  66. printf("%d ", C[i]);
  67. }
  68. printf("\n");
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0.01s 5284KB
stdin
12 3 4 5 6
2 4 5 6 7
stdout
Enter the size of the arrays (N <= 100): Array A: 10 5 5 3 4 10 3 8 2 5 3 6 
Array B: 6 9 6 2 7 9 4 2 6 8 10 7 
Array C (Sum of A and B): 16 14 11 5 11 19 7 10 8 13 13 13