0% found this document useful (0 votes)
29 views16 pages

Adish

The document contains code for implementing thread-safe calculation of Fibonacci numbers using mutexes and condition variables. It defines global variables to store the Fibonacci numbers, a mutex, and condition variable. Multiple threads calculate successive Fibonacci numbers by waiting on the condition variable to access the next index.

Uploaded by

dwarkeshd4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views16 pages

Adish

The document contains code for implementing thread-safe calculation of Fibonacci numbers using mutexes and condition variables. It defines global variables to store the Fibonacci numbers, a mutex, and condition variable. Multiple threads calculate successive Fibonacci numbers by waiting on the condition variable to access the next index.

Uploaded by

dwarkeshd4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

#include <stdio.

h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_KEY 12345
#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {


if (argc < 2) {
fprintf(stderr, "Usage: %s <command>\n", argv[0]);
exit(EXIT_FAILURE);
}
int shmid;
struct timeval *shared_memory;
shmid = shmget(SHM_KEY, sizeof(struct timeval), IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
shared_memory = (struct timeval *)shmat(shmid, NULL, 0);
if (shared_memory == (struct timeval *)(-1)) {
perror("shmat");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
struct timeval start_time;
gettimeofday(&start_time, NULL);
*shared_memory = start_time;
if (execvp(argv[1], &argv[1]) == -1) {
perror("execvp");
exit(EXIT_FAILURE);
}
} else {
wait(NULL);
struct timeval start_time = *shared_memory;
struct timeval end_time;
gettimeofday(&end_time, NULL);
double elapsed_time = (end_time.tv_sec - start_time.tv_sec) +
(end_time.tv_usec - start_time.tv_usec) / 1e6;
printf("Elapsed time: %.5f seconds\n", elapsed_time);
shmdt(shared_memory);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <command>\n", argv[0]);
exit(EXIT_FAILURE);
}
int pipe_fd[2];
struct timeval start_time;
if (pipe(pipe_fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
close(pipe_fd[0]);
gettimeofday(&start_time, NULL);
if (write(pipe_fd[1], &start_time, sizeof(struct timeval)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
if (execvp(argv[1], &argv[1]) == -1) {
perror("execvp");
exit(EXIT_FAILURE);
}
} else {
close(pipe_fd[1]);
wait(NULL);
struct timeval end_time;
double elapsed_time;
if (read(pipe_fd[0], &start_time, sizeof(struct timeval)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
gettimeofday(&end_time, NULL);
elapsed_time = (end_time.tv_sec - start_time.tv_sec) +
(end_time.tv_usec - start_time.tv_usec) / 1e6;
printf("Elapsed time: %.5f seconds\n", elapsed_time);
close(pipe_fd[0]); /
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MIN_PID 300
#define MAX_PID 5000
#define cb CHAR_BIT
unsigned char *b;
int sz = MAX_PID - MIN_PID + 1;
int allocate_map();
int allocate_pid();
void release_pid(int pid);
int main() {
int map = allocate_map();
if (map == 1) {
printf("\nData Structure initialized.\n");
int id = 0, i = 0;
while (i < 3) { // Changed to allocate 3 processes for demonstration
int val = allocate_pid();
if (val != -1)
printf("\nProcess %d: pid = %d", i + 1, val);
else {
printf("\nFailed to allocate pid for Process %d", i + 1);
break;
}
i++;
}
release_pid(503); printf("\nProcess 503 released.");
release_pid(505); printf("\nProcess 505 released.");
int val = allocate_pid();
if (val != -1)
printf("\nAnother process: pid = %d\n", val);
else
printf("\nFailed to allocate another pid.\n");
} else
printf("\nFailed to initialize data structure.\n");
return 0;
}
int allocate_map() {
b = (unsigned char *)malloc((sz + cb - 1) / cb * sizeof(char));
if (b == NULL) return -1; // Check if allocation failed
for (int i = 0; i < sz / cb; ++i) // Initialize all bits to 0
b[i] = 0;
return 1;
}
int allocate_pid() {
for (int i = 0; i < sz; ++i) {
int index = i / cb;
int bit = i % cb;
int pid = (b[index] >> bit) & 1;
if (!pid) { // If bit is not set (pid is available)
b[index] |= (1 << bit); // Set the bit
return i + MIN_PID; // Return the allocated pid
}
}
return -1; // If no pid is available
}
void release_pid(int pid) {
if (pid < MIN_PID || pid > MAX_PID) {
printf("\nInvalid PID: It should lie between %d and %d.", MIN_PID,
MAX_PID);
return;
}
int index = pid - MIN_PID;
int bit = index % cb;
index /= cb;
b[index] &= ~(1 << bit); // Clear the bit
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 3
double average;
int minimum;
int maximum;
void *calculate_average(void *param) {
int *numbers = (int *)param;
double sum = 0;
int i;
for (i = 0; numbers[i] != -1; i++) {
sum += numbers[i];
}
average = sum / i;
pthread_exit(NULL);
}
void *calculate_minimum(void *param) {
int *numbers = (int *)param;
minimum = numbers[0];
for (int i = 1; numbers[i] != -1; i++) {
if (numbers[i] < minimum) {
minimum = numbers[i];
}
}
pthread_exit(NULL);
}
void *calculate_maximum(void *param) {
int *numbers = (int *)param;
maximum = numbers[0];
for (int i = 1; numbers[i] != -1; i++) {
if (numbers[i] > maximum) {
maximum = numbers[i];
}
}
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <number1> <number2> ... <numberN>\n", argv[0]);
return 1;
}
int numbers[argc];
for (int i = 1; i < argc; i++) {
numbers[i - 1] = atoi(argv[i]);
}
numbers[argc - 1] = -1;
pthread_t threads[NUM_THREADS];
pthread_create(&threads[0], NULL, calculate_average, numbers);
pthread_create(&threads[1], NULL, calculate_minimum, numbers);
pthread_create(&threads[2], NULL, calculate_maximum, numbers);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("The average value is %.2f\n", average);
printf("The minimum value is %d\n", minimum);
printf("The maximum value is %d\n", maximum);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
void *print_primes(void *param) {
int n = *((int *)param);
printf("Prime numbers up to %d:\n", n);
for (int i = 2; i <= n; i++) {
if (is_prime(i)) {
printf("%d ", i);
}
}
printf("\n");
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
int num = atoi(argv[1]);
if (num <= 0) {
printf("Please enter a positive integer.\n");
return 1;
}
pthread_t tid;
pthread_create(&tid, NULL, print_primes, &num);
pthread_join(tid, NULL);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define MIN_PID 300
#define MAX_PID 5000
#define NUM_PID (MAX_PID - MIN_PID + 1)
int *pid_map = NULL;
pthread_mutex_t mutex;
int allocate_map(void) {
pid_map = (int *)calloc(NUM_PID, sizeof(int));
if (pid_map == NULL) {
return -1;
}
pthread_mutex_init(&mutex, NULL);
return 1;
}
int allocate_pid(void) {
if (pid_map == NULL) {
return -1;
}
pthread_mutex_lock(&mutex);
for (int i = 0; i < NUM_PID; ++i) {
if (pid_map[i] == 0) {
pid_map[i] = 1;
pthread_mutex_unlock(&mutex);
return i + MIN_PID;
}
}
pthread_mutex_unlock(&mutex);
return -1;
}
void release_pid(int pid) {
if (pid_map != NULL && pid >= MIN_PID && pid <= MAX_PID) {
pthread_mutex_lock(&mutex);
pid_map[pid - MIN_PID] = 0;
pthread_mutex_unlock(&mutex);
}
}
void *test_pid_manager(void *arg) {
int pid = allocate_pid();
if (pid != -1) {
printf("Allocated PID: %d\n", pid);
sleep(2);
release_pid(pid);
printf("Released PID: %d\n", pid);
} else {
printf("Unable to allocate PID\n");
}
return NULL;
}
int main() {
if (allocate_map() == -1) {
fprintf(stderr, "Failed to allocate pid map\n");
return 1;
}
pthread_t threads[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, test_pid_manager, NULL);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
free(pid_map);
pthread_mutex_destroy(&mutex);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_FIB 20
int fib[MAX_FIB];
int next = 0;
int n;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* fib_func(void* arg) {
int i, tmp;
pthread_t tid = pthread_self();
for (i = 0; i < n; i++) {
pthread_mutex_lock(&mutex);
while (next != i) {
pthread_cond_wait(&cond, &mutex);
}
if (i == 0) {
fib[i] = 0;
} else if (i == 1) {
fib[i] = 1;
} else {
fib[i] = fib[i - 1] + fib[i - 2];
}
tmp = next;
next++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
printf("Thread ID: %ld, Fib[%d]: %d\n", (long)tid, i,
fib[i]);
}
pthread_exit(NULL);
}
int main() {
pthread_t tid;
int i;
printf("No. of terms:\n");
scanf("%d", &n);
if (n > MAX_FIB) {
printf("Number of terms exceeds maximum allowed.\n");
return -1;
}
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
if (pthread_create(&tid, NULL, fib_func, NULL) != 0) {
printf("Failed to create thread.\n");
return -1;
}
pthread_t parent_tid = pthread_self();
printf("Parent thread ID: %ld\n", (long)parent_tid);
for (i = 0; i < n; i++) {
pthread_mutex_lock(&mutex);
while (next != i) {
pthread_cond_wait(&cond, &mutex);
}
printf("Thread ID: %ld, Fib[%d]: %d\n", (long)tid, i,
fib[i]);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_join(tid, NULL);
printf("Child thread exited.\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct StackNode {
int data;
struct StackNode* next;
} StackNode;
typedef struct {
StackNode* top;
pthread_mutex_t mutex;
} Stack;
void initStack(Stack* stack) {
stack->top = NULL;
pthread_mutex_init(&stack->mutex, NULL);
}
void push(int data, Stack* stack) {
StackNode* newNode = malloc(sizeof(StackNode));
newNode->data = data;
pthread_mutex_lock(&stack->mutex);
newNode->next = stack->top;
stack->top = newNode;
pthread_mutex_unlock(&stack->mutex);
}
int pop(Stack* stack) {
pthread_mutex_lock(&stack->mutex);
if (!stack->top) {
pthread_mutex_unlock(&stack->mutex);
return -1;
}
StackNode* temp = stack->top;
int data = temp->data;
stack->top = stack->top->next;
free(temp);
pthread_mutex_unlock(&stack->mutex);
return data;
}
int main() {
Stack stack;
initStack(&stack);
push(5, &stack);
push(10, &stack);
push(15, &stack);
int value;
while ((value = pop(&stack)) != -1) {
printf("Popped value: %d\n", value);
}
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define MAX_LINE_LENGTH 1024

struct ThreadData {
FILE *file_ptr;
int thread_id;
};
void *readFileLines(void *arg) {
struct ThreadData *td = (struct ThreadData *)arg;
char line[MAX_LINE_LENGTH];
int line_number = 1;
while (fgets(line, MAX_LINE_LENGTH, td->file_ptr) != NULL) {
if ((line_number % 2 == 1 && td->thread_id == 1) || (line_number % 2 == 0
&& td->thread_id == 2)) {
printf("Thread %d: %s", td->thread_id, line);
}
line_number++;
}
pthread_exit(NULL);
}
int main() {
FILE *file_ptr;
pthread_t thread1, thread2;
struct ThreadData td1, td2;
file_ptr = fopen("info.txt", "a+");
if (file_ptr == NULL) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
td1.file_ptr = file_ptr;
td1.thread_id = 1;
td2.file_ptr = file_ptr;
td2.thread_id = 2;
pthread_create(&thread1, NULL, readFileLines, (void *)&td1);
pthread_create(&thread2, NULL, readFileLines, (void *)&td2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
rewind(file_ptr);
char line[MAX_LINE_LENGTH];
while (fgets(line, MAX_LINE_LENGTH, file_ptr) != NULL) {
int random_num = rand() % 1000;
fprintf(file_ptr, " %d\n", random_num);
}
fclose(file_ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct ThreadData {
int *heap_data;
int data_size;
};
void *childThread(void *arg) {
struct ThreadData *td = (struct ThreadData *)arg;
printf("Child Process - Heap Data: ");
for (int i = 0; i < td->data_size; i++) {
printf("%d ", td->heap_data[i]);
}
printf("\n");
pthread_exit(NULL);
}
int main() {
int data_size = 5;
int *heap_data = (int *)malloc(data_size * sizeof(int));
for (int i = 0; i < data_size; i++) {
heap_data[i] = i + 1;
}
printf("Parent Process - Heap Data: ");
for (int i = 0; i < data_size; i++) {
printf("%d ", heap_data[i]);
}
printf("\n");

struct ThreadData td;


td.heap_data = heap_data;
td.data_size = data_size;
pthread_t thread;
pthread_create(&thread, NULL, childThread, (void *)&td);
pthread_join(thread, NULL);
free(heap_data);
return 0;
}

You might also like