20bce2126 PDC Lab Da 3
20bce2126 PDC Lab Da 3
20BCE2126
PDC lab DA-3
Algorithm:
return result;
}
return result;
}
int main()
{
int array[ARRAY_SIZE];
linear_start = omp_get_wtime();
#pragma omp parallel
{
#pragma omp single nowait
{
int linear_result = linear_search(array, ARRAY_SIZE, SEARCH_VALUE);
if (linear_result != -1)
{
printf("Linear search found %d at index %d\n", SEARCH_VALUE, linear_result);
}
else
{
printf("Linear search did not find %d\n", SEARCH_VALUE);
}
}
}
linear_end = omp_get_wtime();
binary_start = omp_get_wtime();
#pragma omp parallel
{
#pragma omp single nowait
{
int binary_result = binary_search(array, ARRAY_SIZE, SEARCH_VALUE);
if (binary_result != -1)
{
printf("Binary search found %d at index %d\n", SEARCH_VALUE, binary_result);
}
else
{
printf("Binary search did not find %d\n", SEARCH_VALUE);
}
}
}
binary_end = omp_get_wtime();
return 0;
}
Output:
2. Develop an OpenMP program to perform two-dimensional matrix
vector addition and multiplication using sections clauses
Algorithm:
Matrix-Vector Addition Algorithm:
Code:
#include <stdio.h>
#include <omp.h>
#define N 4
void matrixVectorAddition(double matrix[][N], double vector[], double
result[]) {
int i, j;
int main() {
double matrix[N][N];
double vector[N];
double result[N];
return 0;
}
Output:
Algorithm:
Producer Algorithm:
Consumer Algorithm:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <unistd.h>
#define BUFFER_SIZE 5
#define NUM_PRODUCERS 2
#define NUM_CONSUMERS 2
#define NUM_ITEMS 10
int buffer[BUFFER_SIZE];
int itemCount = 0;
int in = 0;
int out = 0;
void producer() {
int item;
while (1) {
item = rand() % 100;
usleep(100000);
}
}
void consumer() {
int item;
while (1) {
#pragma omp critical
{
if (itemCount > 0) {
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
itemCount--;
printf("Consumed: %d (Items in buffer: %d)\n", item, itemCount);
}
}
usleep(150000);
}
}
int main() {
omp_set_num_threads(NUM_PRODUCERS + NUM_CONSUMERS);
return 0;
}
Output: