0% found this document useful (0 votes)
4 views

cs604pp

The provided C code demonstrates the use of pthreads to create two threads: one for calculating and printing the squares of an integer array, and another for reversing and printing a given string. The main function initializes an array of integers and prompts the user for a string, then creates and joins the threads to execute their respective tasks. The program concludes by exiting the main function after both threads have completed their execution.

Uploaded by

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

cs604pp

The provided C code demonstrates the use of pthreads to create two threads: one for calculating and printing the squares of an integer array, and another for reversing and printing a given string. The main function initializes an array of integers and prompts the user for a string, then creates and joins the threads to execute their respective tasks. The program concludes by exiting the main function after both threads have completed their execution.

Uploaded by

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

Code:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
void *calculate_squares(void *arg)
{
int *arr = (int*)arg;
printf("\nIn Frist Thread\n");
printf("Printing the actual contents of array\n");
for(int i = 0; i < 10; i++)
{
printf("%d\n" , arr[i]);
}
printf("\nPrinting the Squares of Numbers in the Array\n");
for (int i =0; i < 10; i++)
{
printf("%d^2 = %d\n" , arr[i], arr[i] * arr[i]);
}
pthread_exit(NULL);

void *reverse_string(void *arg)


{
char *str = (char *)arg;
int len = strlen(str);
char reversed[len + 1];
for(int i = 0; i < len; i++)
{
reversed[i] = str[len - 1 - i];
}
reversed[len] = '\0';
printf("\nIn Second Thread, Printing the Reverse String...\n");
printf("%s\n" , reversed);
pthread_exit (NULL);
}

int main()
{

int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,};


char str[100];
printf("Enter a String To Pass T2: \n");
scanf("%s" , str);
pthread_t t1, t2;

if(pthread_create(&t2, NULL, reverse_string, (void *)str) != 0)


{
perror("Failed to Create Thread T2");
return 1;
}
pthread_join(t2, NULL);
if(pthread_create(&t1, NULL, calculate_squares, (void *)array) != 0)
{
perror("Failed to Create Thread T1");
return 1;
}
pthread_join(t1, NULL);
printf("\nExiting the main function\n");
return 0;
}

Screenshot of output:

You might also like