The collatz conjecture concerns what happns when we take any
The collatz conjecture concerns what happns when we take any postive integer n and apply the following algorithm:
n ={ n/2 if n is even 3n+ 1 if n is odd
The conjecture states that when this algorithm is continually applied all positive integers will eventually reach 1. Write a C program using POSIX thread that generates this sequence in the child thread. The starting number will be provided from the command line. The parent can then output the sequence when the child thread completes. The parent process will progress through the following steps:
a. Establish the global variables to store the sequence.
b. Create the child thread and wait for it to terminate.
c. Output the sequence.
d. Exit.
One area of concern with cooperating threads involves synchronization issues. In this exercise, the parent and child threads must be coordinated so that the parent does not output the sequence until the child finishes execution. The parent thread will invoke pthread_join(), which will suspend it until the child thread exits.
Solution
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
int a[20];
void *compute(void *);
int main()
{
pthread_t thread;
int i=0,n,*p;
printf(\"\ Enter the first number:\");
scanf(\"%d\",&n);
p=&n;
pthread_create(&thread, NULL, compute,(void *)p);
pthread_join(thread,NULL);
printf(\"\ \ The array returned by thread is...\ \");
while(a[i]!=\'\\0\')
{
printf(\"%d\",a[i]);
i++;
}
}
void *compute(void *m)
{
int j=0,n,*p;
p=(int *)m;
n=*p;
printf(\"%d\",n);
while(n!=1)
{
if(n/2==0)
n=n/2;
else
n=3*n+1;
a[j]=n;
j++;
}
}
