#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define MAX_SIZE 100 // Max size of the arrays
// Declare the arrays A, B, and C globally
int A[MAX_SIZE], B[MAX_SIZE], C[MAX_SIZE];
int N; // Size of the arrays
// Thread function to compute C[i] = A[i] + B[i]
void *vector_sum(void *arg) {
int index = *(int *)arg; // The thread index is passed as an argument
C[index] = A[index] + B[index];
pthread_exit(NULL);
}
int main() {
// Seed the random number generator
// Get the size of the arrays (N)
printf("Enter the size of the arrays (N <= 100): ");
// Initialize arrays A and B with random values between 0 and 10
for (int i = 0; i < N; i++) {
A
[i
] = rand() % 11; // Random number between 0 and 10 B
[i
] = rand() % 11; // Random number between 0 and 10 }
// Create an array of threads
pthread_t threads[MAX_SIZE];
// Create threads to compute C[i] = A[i] + B[i]
for (int i = 0; i < N; i++) {
int *index
= malloc(sizeof(*index
)); *index = i;
if (pthread_create(&threads[i], NULL, vector_sum, (void *)index) != 0) {
perror("Error creating thread"); return 1;
}
}
// Join the threads to ensure they complete before printing the result
for (int i = 0; i < N; i++) {
pthread_join(threads[i], NULL);
}
// Print the arrays A, B, and C
for (int i = 0; i < N; i++) {
}
for (int i = 0; i < N; i++) {
}
printf("Array C (Sum of A and B): "); for (int i = 0; i < N; i++) {
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHB0aHJlYWQuaD4KI2luY2x1ZGUgPHRpbWUuaD4KCiNkZWZpbmUgTUFYX1NJWkUgMTAwICAvLyBNYXggc2l6ZSBvZiB0aGUgYXJyYXlzCgovLyBEZWNsYXJlIHRoZSBhcnJheXMgQSwgQiwgYW5kIEMgZ2xvYmFsbHkKaW50IEFbTUFYX1NJWkVdLCBCW01BWF9TSVpFXSwgQ1tNQVhfU0laRV07CmludCBOOyAgLy8gU2l6ZSBvZiB0aGUgYXJyYXlzCgovLyBUaHJlYWQgZnVuY3Rpb24gdG8gY29tcHV0ZSBDW2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gICAgaWYgKHB0aHJlYWRfY3JlYXRlKCZ0aHJlYWRzW2ldLCBOVUxMLCB2ZWN0b3Jfc3VtLCAodm9pZCAqKWluZGV4KSAhPSAwKSB7CiAgICAgICAgICAgIHBlcnJvcigiRXJyb3IgY3JlYXRpbmcgdGhyZWFkIik7CiAgICAgICAgICAgIHJldHVybiAxOwogICAgICAgIH0KICAgIH0KCiAgICAvLyBKb2luIHRoZSB0aHJlYWRzIHRvIGVuc3VyZSB0aGV5IGNvbXBsZXRlIGJlZm9yZSBwcmludGluZyB0aGUgcmVzdWx0CiAgICBmb3IgKGludCBpID0gMDsgaSA8IE47IGkrKykgewogICAgICAgIHB0aHJlYWRfam9pbih0aHJlYWRzW2ldLCBOVUxMKTsKICAgIH0KCiAgICAvLyBQcmludCB0aGUgYXJyYXlzIEEsIEIsIGFuZCBDCiAgICBwcmludGYoIkFycmF5IEE6ICIpOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBOOyBpKyspIHsKICAgICAgICBwcmludGYoIiVkICIsIEFbaV0pOwogICAgfQogICAgcHJpbnRmKCJcbiIpOwoKICAgIHByaW50ZigiQXJyYXkgQjogIik7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IE47IGkrKykgewogICAgICAgIHByaW50ZigiJWQgIiwgQltpXSk7CiAgICB9CiAgICBwcmludGYoIlxuIik7CgogICAgcHJpbnRmKCJBcnJheSBDIChTdW0gb2YgQSBhbmQgQik6ICIpOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBOOyBpKyspIHsKICAgICAgICBwcmludGYoIiVkICIsIENbaV0pOwogICAgfQogICAgcHJpbnRmKCJcbiIpOwoKICAgIHJldHVybiAwOwp9Cg==