I would like to calculate a mathematic summation in c using threads.
(∑x^i ,From 0 to N) Each threads should calculate each terms of the summation and finally in the main the program should sum all of them and print them.
How should I make the number of threads dynamically?
Here is my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
pthread_t sadaf[10];
int i,a[10];
long int x,N;
int sum=0;
pthread_mutex_t mtx;
void *Myfun(void *tid)
{
int *ThreadID=(int *)tid;
pthread_mutex_lock(&mtx);
printf("The thread with id of %d calculated x^i\n",*ThreadID);
a[*ThreadID]=pow(x,*ThreadID);
sum=sum+a[*ThreadID];
pthread_mutex_unlock(&mtx);
}
int main()
{
int d[10] = {0};
printf("->**************************************************************************<-\n");
printf("This program will calculate the following function:\n-> ∑x^i ,From 0 to N \n");
printf("->**************************************************************************<-\n");
printf("Please enter x:\n");
scanf("%ld",&x);
printf("Please enter N:\n");
scanf("%ld",&N);
for (i=0; i<N; i++)
{
d[i] = i;
pthread_create(&sadaf[i],NULL,Myfun,(void *)&d[i]);
}
for (i=0; i<N; i++)
{
pthread_join(sadaf[i],NULL);
}
printf("The sum is: %d\n",sum);
}
The d array can hold 10 values, so if N is greater than 10, you have an out of bounds problem:
int d[10] = {0};
...
for (i=0; i<N; i++)
{
d[i] = i; // if i > 10 => you access out of bounds => problem
You have the same problem with other arrays too.
You have only 10 pthreads defined at the beginning.
pthread_t sadaf[10];
Creating more than 10 threads will cause the undefined behaviour.
Related
My Code does not print anything with gcc. I tried to flush the buffer, but does not make a difference.
#include <stdio.h>
int main() {
int foo[65];
for(int i; i < 64; ++i) {
printf("Number: Count: \n");
}
}
If remove the 3 line it works.
#include <stdio.h>
int main() {
for(int i; i < 64; ++i) {
printf("Number: Count: \n");
}
}
Is this a bug in gcc because this array is not related to the printf call.
Try switching your code to the following:
#include <stdio.h>
int main() {
int foo[65];
for(int i=0; i < 64; ++i) {
printf("Number: Count: \n");
}
}
Which will just print the following 64 times:
Number: Count:
Are you trying to print out the contents of your array foo[65]? If so that is also uninitialized so you'll need to insert integers first before you view them.
Initialize i, otherwise it could be any random number. Unlike some other languages, C does not automatically initialize variables to 0 (or the equivalent) unless they are global variables.
#include <stdio.h>
int main() {
int foo[65];
for(int i = 0; i < 64; ++i) {
printf("Number: Count: \n");
}
}
I have got troubles with my code.
The following code starts n threads that compete to find the max value of each diagonal of n different matrices.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <time.h>
#include <semaphore.h>
void crea_matrix(int **);
void trova_max(void *);
struct bin_sem
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int cnt;
} shared= {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER };
int n,**matrix,max;
int main ()
{
int i;
srand(time(NULL));
printf("N of matrices: \n");
scanf("%d", &n);
int **matrix = (int **)malloc(3 * sizeof(int *));
for (i=0; i<3; i++)
matrix[i] = (int *)malloc(3 * sizeof(int));
pthread_t *tids;
tids=malloc(n*sizeof(pthread_t));
for(i=0;i<n;i++)
pthread_create(tids+i,NULL,trova_max,matrix);
for(i=0;i<n;i++)
{
pthread_mutex_lock(&shared.mutex);
max=0;
crea_matrix(matrix);
shared.cnt=i;
pthread_cond_signal(&shared.cond);
pthread_mutex_unlock(&shared.mutex);
sleep(1);
}
for(i=0;i<n;i++)
pthread_join(tids[i],NULL);
}
void crea_matrix(int **matrix)
{
int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
matrix[i][j]=rand()%101;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",matrix[i][j]);
printf("\n");
}
}
void trova_max(void* arg)
{
int i=0, j=0;
int **arr2d;
arr2d=(int**)arg;
do
{
pthread_mutex_lock(&shared.mutex);
pthread_cond_wait(&shared.cond,&shared.mutex);
printf("\nThread: %ld took control of the mutex...\n",(long int) pthread_self());
for(i=0;i<3;i++)
{
if(arr2d[i][i]>max)
max=arr2d[i][i];
printf("\nFirst diag max: %d\n",max);
}
i=0;
for (j=2;j>=0;j--)
{
printf("\nSecond diag max: %d\n",max);
if (arr2d[i][j]>max)
max=arr2d[i][j];
i++;
}
printf("Max found: %d,matrix n° %d", max,shared.cnt);
pthread_mutex_unlock(&shared.mutex);
} while(shared.cnt !=n-1);
pthread_exit(NULL);
}
The thing is, most of my code works, but when the max evaluations are done, only 1 thread gets access to the pthread_exit(NULL); line.
I am struggling to find a solution, Hope you can help me.
Thanks.
Referring to this question: Is it guaranteed that pthread_cond_signal will wake up a waiting thread?
It is possible that the remaining threads are still blocked on pthread_cond_wait. Doing a final pthread_cond_broadcast before the join will release all the blocked threads.
However, this solution will bring its own set of problems as all the threads will eventually execute the body of the loop. You may have to add an extra check for shared.cnt != n-1. That has to be done atomically though as noticed in one of the comments.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int reverse(int a[20],int n);
int main()
{
int a[20];
int n;
printf("enter the number of elements \n");
scanf("%d",&n);
printf("enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d ",&a[i]);
}
reverse(a,n);
return 0;
}
int reverse(int a[20],int n)
{
for(int i=n-1;i>=0;i--)
{
printf("%d ",a[i]);
}
return 0;
}
here if I input n=4 then during runtime i have to take 5 elements and then it reverses.For eg if i take n=4 and then for no of elements i have to take 1,2,3,4,5 and then only output is coming as 4 3 2 1.Why? is my logic wrong? also in this code I am unable to take the number of elements of arrays in a straight line, like 1 2 3 4.When I am entering the number each number is entering in new line .I am a novice programmer in C and thus having these doubts.Please anyone explain...
The problem with your code is the extra space after %d in your scanf line where you accept array elements i.e.
for(int i=0;i<n;i++)
{
scanf("%d ",&a[i]); //should be scanf("%d",&a[i]);
}
Change that and you're good to go.
Here is your entire program refactored to work correctly:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int reverse(int a[20], int n)
int main()
{
int a[20];
int n;
printf("enter the number of elements \n");
scanf("%d",&n);
printf("enter the array elements\n");
for (int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
reverse(a,n);
return 0;
}
int reverse(int a[20], int n)
{
int mid = n/2;
for (int i=0; i < mid; ++i)
{
int temp = a[n-i-1];
a[n-i-1] = a[i];
a[i] = temp;
}
return 0;
}
Why is this code not working properly?
The intent of this code is to generate and print two random numbers separately
as many times as user choose.
M.T.
Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define random(x) rand() % x
#define randomize srand((unsigned)time(NULL))
int i=0;
int j=0;
int x=0;
int y=0;
int main(void)
{
printf("insert number of loops:");
scanf("%d",x);
for(y=0;y=x;y++)
{
randomize;
i = random(51);
j = random(51);
printf("%d\n",i);
printf("%d\n",j);
}
return 0;
}
You are calling srand more than once. Place randomize; outside the for loop. Another problem is with the statement
scanf("%d",x);
you forget to place & before x.
Also You need to correct the loop condition y = x to y < x as mentioned in comment by #Cool Guy.
solved, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define random(x) rand() % x
#define randomize srand((unsigned)time(NULL))
int i=0;
int j=0;
int x=0;
int y=0;
int main(void)
{
printf("insert number of loops:");
scanf("%d",&x);
randomize;
for(y=0;y<x;y++)
{
i = random(51);
j = random(51);
printf("%d\n",i);
printf("%d\n",j);
}
return 0;
}
I want to create 2 threads, one does the max and one gives the average of a list of numbers entered in the command line.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <limits.h>
void * thread1(int length, int array[] )
{
int ii = 0;
int smallest_value = INT_MAX;
for (; ii < length; ++ii)
{
if (array[ii] < smallest_value)
{
smallest_value = array[ii];
}
}
printf("smallest is: %d\n", smallest_value);
}
void * thread2()
{
printf("\n");
}
int main()
{
int average;
int min;
int max;
int how_many;
int i;
int status;
pthread_t tid1,tid2;
printf("How many numbers?: ");
scanf("%d",&how_many);
int ar[how_many];
printf("Enter the list of numbers: ");
for (i=0;i<how_many;i++){
scanf("%d",&ar[i]);
}
//for(i=0;i<how_many;i++)
//printf("%d\n",ar[i]);
pthread_create(&tid1,NULL,thread1(how_many,ar),NULL);
pthread_create(&tid2,NULL,thread2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
exit(0);
}
I just made the first thread, which is to print out the min. number, but I have the following errors when compiling:
How many numbers?: 3
Enter the list of numbers: 1
2
3
Smallest: 1
Segmentation fault
How should I go on and fix the seg. fault?
You can't pass arguments like you're trying to in pthread_create.
Create a structure like:
struct args_t
{
int length;
int * array;
};
then initialize a structure with your array and length.
args_t *a = (args_t*)malloc(sizeof(args_t));
//initialize the array directly from your inputs
Then do
pthread_create(&tid1,NULL,thread1,(void*)a);
Then just cast the argument back to an args_t.
Hope that helps.