I need to create a program which calculates recursion (for certain sequence). When I use int and decleare a recursion, that calculates values without floating numbers (like fibonacci sequence, which returns only neutral numbers) it works. However, when trying to use sequences based on divison (with floating numbers) it displays an error as below:
error: cannot convert to a floating type
pthread_exit((void*)(float)wynik;
How should I change the code (or actually a function *ciag, because problem is with that one), that it will accept floating numbers?
Function which works fine (with int)
int* fibo(int n){
int wynik;
int* n1;
if (n==0) wynik=0;
else if (n==1) wynik=1;
else wynik =(int)fibo((int)(n-1))+(int)fibo((int)(n-2));
return (int*)wynik;
pthread_exit((void*)wynik);
}
And the one I have problem with (with float, but same happens when I try to use double)
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#define COUNT 2
float *ciag(int n) {
float wynik;
if(n == 0)
wynik = -1;
else
wynik = ((float)ciag(n - 1)*(n + 1))/(float)ciag(n - 1)*(float)ciag(n - 1)*(float)ciag(n - 1);
return(float *)wynik;
pthread_exit((void *)wynik);
}
void *drugi_watek(void* wynik) {
int i = 1;
while(i == 0) {
printf("#");
fflush(stdout);
usleep(300000);
pthread_exit((void*)wynik);
}
}
int main() {
pthread_t watek_1, watek_2;
int n;
float wynik;
printf("Podaj numer ciagu: ");
scanf("%d", &n);
pthread_create(&watek_1, NULL,(void*)&ciag, n);
pthread_create(&watek_2, NULL, &drugi_watek, NULL);
if(!pthread_join(watek_1,(void**)&wynik))
{
pthread_cancel(watek_2);
}
printf("Element numer %f ciagu: %f\n", &n, &wynik);
return 0;
}
You cannot directly convert a float to a void * or vice-versa.
The cleanest way to do this is to allocate space for a float somewhere -- either from the heap or on the caller's stack -- and have the thread function store the float value into the pointed-to variable (float * is easily convertible to/from void *). If you go this route and allocate the value on the stack, you need to make sure that the caller's stack frame remains in existence until the thread completes.
Since the function you want to call is recursive, having it as the thread function is too cumbersome. Better to make it a separate (ordinary) function that takes an int argument and returns a float. Then make a wrapper function that will be the target for pthread_create.
And since you also need to pass an argument int to your function, it's easiest to allocate a struct to contain both argument and return value (a union would also work since you don't really need argument and return value at the same time). Here's a sample program that demonstrates the pattern:
#include <pthread.h>
#include <stdio.h>
static float ciag(int n)
{
float wynik;
if(n == 0)
wynik = -1;
else
wynik = (ciag(n - 1)*(n + 1))/ciag(n - 1)*ciag(n - 1)*ciag(n - 1);
return wynik;
}
typedef struct {
int i;
float f;
} if_t;
static void *ciag_thread(void *vp)
{
if_t *ifp = vp;
// Obtain argument from the structure and put the result back into the structure
ifp->f = ciag(ifp->i);
return vp;
}
int main()
{
pthread_t watek_1;
int n = 4;
// Obtain n however you like. Then place argument into structure allocated
// on the stack
if_t arg;
arg.i = n;
// Pointer to structure is implicitly convertible to (void *)
pthread_create(&watek_1, NULL, ciag_thread, &arg);
pthread_join(watek_1, NULL);
printf("Thread returned %f\n", arg.f);
return 0;
}
One other note. Your code seems to suggest that pthread_join on the first thread might sometimes fail. That will not happen here. Though for large values of n, it may take a very long time to complete, due to the quartic nature of your function.
Related
There are some problems thatconfuse me:
The callee function needs return a structure, but there is not a structure statment in caller function.
If i have to write the declaration in the calling function,it can not be called packaging function.
If i return a structure pointer by callee function, but the structure is in the stack of the called function and will be destroyed after the end, which is not safe. Sometimes i get some warning or even wrong!
I have a limited ideas but it not good. I put the structure into the heap by malloc and return the void*pointer. But this gave birth to a new problem :after each call to this function, in the caller, I cannot release the heap through the free() function,the complier can not identify variable name of structure pointer. I think it verey dangerous. I want when the callee function quit,it can be released by itself.
This is the first time I came to this website to ask questions and I just came into contact with c language,If there is something stupid please point it out.
I have to write the structure declaration outside. This program for judging prime number, and I want to package the founction "judging_number". I do not want to write the structure declaration when I want to call the founction "judging_number".
Please give me some help, I would be very grateful.
Sorry, this is my fault. I compiled it with clang++, I saved it as *.cpp, but I wrote c code in it.
What I mean is, can I put the declaration in the called function to realize the function modularization, how can I not declare a structure before calling the function? Is there any way I can not write a declaration. Like use founction in stdio.h.It is as convenient as using the functions of the standard library. Only need to write a line of function call and pass parameters, the called function can return multiple results.
#include <stdio.h>
struct boundary{
int L;
int R;
};boundary *range;
int *get_number()
{
int *nPtr = (int *)malloc(sizeof(int));
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", nPtr);
if (*nPtr == 1)
{
exit(1);
}
} while (*nPtr < 1);
printf("The object is %d\r\n", *nPtr);
return nPtr;
}
int judg_number(int N,boundary range){
if (N%range.L==0&&N!=2){
printf("The number %d is a composite number.\r\n", N);
}
else{
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
boundary* get_range(int N){
boundary *Ptr = (boundary *)malloc(sizeof(boundary));
*Ptr = {2,N-1};
printf("The range is between %d and %d .\r\n", Ptr->L, Ptr->R);
return Ptr;
}
int main(int argc,char**argv,char**env){
int*N;
while(1){
N=get_number();
range=get_range(*N);
judg_number(*N, *range);
free(N);
free(range);
}
getchar();
getchar();
return 0;
}
You dont need dynamic memory allocation here. If you want to retun an int, retun an int. If you want to retun a stuct return a struct.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
struct boundary {
int L;
int R;
};
struct boundary range;
int get_number()
{
int n;
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", &n);
if (n == 1)
{
exit(1);
}
} while (n < 1);
printf("The object is %d\r\n", n);
return n;
}
int judg_number(int N, struct boundary range) {
if (N % range.L == 0 && N != 2) {
printf("The number %d is a composite number.\r\n", N);
}
else {
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
struct boundary get_range(int N) {
struct boundary b = { 2, N - 1 };
printf("The range is between %d and %d .\r\n", b.L, b.R);
return b;
}
int main(int argc, char** argv, char** env) {
int N;
while (1) {
N = get_number();
range = get_range(N);
judg_number(N, range);
}
getchar();
getchar();
return 0;
}
BTW:
boundary get_range(int N) {... is invalid in C but valid in C++. In C it should be struct boundary get_range(int N) {...
having some trouble finding out the syntax around returning a vector from a pthread function. Here's currently what I have:
typedef struct vectorData {
vector v1;
vector v2;
} vectorData;
void *vectorAddThread(void *arg) {
vectorData *data = (vectorData *)arg;
vector v1 = data->v1;
vector v2 = data->v2;
vector result = {v1->x + v2->x, v1->y + v2->y, v1->z + v2->z};
return (void*) result;
}
I'm getting errors on the last two lines about the return result, and the the adding part. Thanks
You can't convert a struct to a void * pointer. You need dynamically allocate a vector in your case with malloc, and return the pointer.
vector *result = malloc(sizeof(vector));
result->x = ?;
result->y = ?;
result->z = ?;
return (void *)result;
Now that would solve the issue of returning a struct from a function that returns void *. But if you're using pthreads you shouldn't be returning objects from them, you need to pass the vector to it as user data in arg.
This is probably easiest:
typedef struct vectorData {
vector v1;
vector v2;
vector result;
} vectorData;
Saves messing about with dubious thread-stack vars, mallocs etc. and ties the result output directly to the inputs.
The thread start function in pthread library returns a pointer to void. Can return any pointer type by type-casting it to (void *). The return value can be accessed by pthread_join(3).
However, a vector needs the type of element information also. Not sure if type-casting it to (void *) and accessing it again will work fine. Using it as an element of structure seems better.
In the following example, I am returning a pointer to structure from the thread start function. The structure contains a vector and two character arrays. You can change it according to your requirement. I am using two pointers to show that data is copied on the variable used for pthread_join(3).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <vector>
void *functionPthread(void *);
struct retStruct
{
std::vector<int> vecNumber;
char name[20];
char city[20];
};
struct retStruct *r2;
struct retStruct *r1;
int main()
{
int rc, i;
pthread_t th;
r2 = (retStruct*) malloc(sizeof(retStruct));
memset(r2, '\0', sizeof(r2));
if(rc = pthread_create(&th, NULL, &functionPthread, NULL))
{
printf("Thread creation failed, return code %d, errno %d", rc, errno);
}
pthread_join(th, (void**)&r2);
for(i = 0; i < r2->vecNumber.size(); i++)
printf("Vectore element at index %d = %d\n", i, r2->vecNumber.at(i));
printf("Name: %s, City: %s, Vector Number: %d\n", r2->name, r2->city, r2->vecNumber.front());
free(r1);
free(r2);
return 0;
}
void *functionPthread(void *)
{
r1 = (retStruct*) malloc(sizeof(retStruct));
memset(r1, '\0', sizeof(r1));
strcpy(r1->name, "xxxx");
strcpy(r1->city, "yyyy");
r1->vecNumber.push_back(11);
r1->vecNumber.push_back(12);
return r1;
}
I'm writing code for the Dining Philosopher thread problem for N number of philosophers from user input. I get an error for dereferencing void * pointer. What am I doing wrong specifically with passing in the array?
void *philosopher(void *arg_l);
int main()
{
int i,A,B;
scanf("%10d", &A);
scanf("%10d", &B);
printf("You got %d phils and %d turns each\n",A,B);
int args[2];
args[0] = A;
args[1] = B;
pthread_t thread_id[A];
sem_init(&mutex,0,1);
for(i=0;i<A;i++)
sem_init(&S[i],0,0);
for(i=0;i<A;i++)
{
args[2] = phil_num[i];
pthread_create(&thread_id[i],NULL,philosopher,&args);
printf("Philosopher %d is thinking\n",i+1);
}
for(i=0;i<A;i++)
pthread_join(thread_id[i],NULL);
}
void *philosopher(void *arg_l)
{
arg_l[0] = int A;
arg_l[1] = int B;
...
return NULL;
}
Since arg_l has type void *, you can't use the subscript operator [] on it. That would mean each element has type void, which cannot be instantiated. Also, the syntax on the right side of the assignment is not valid.
You need to cast the thread argument to int * before you can use it. Also, you need to pass in args without taking its address, since an array decays into a pointer to the first element when passed to a function.
pthread_create(&thread_id[i],NULL,philospher,args);
...
void *philospher(void *arg_l)
{
int *args = arg_l;
...
}
Your lines like:
arg_l[0] = int A;
are completely broken. You would get away with:
int A = ((int *)arg_l)[0];
You cannot dereference a void * validly, nor can you index them (in part because that requires dereferencing, in part because in standard C — as opposed to GNU C — the sizeof(void) is undefined). You need to convert to an appropriate type with a cast and then derefence, as shown.
Note: args[2] = phil_num[i]; is writing out of bounds (you define int args[2]; but it appears you need int args[3];.
You have to pass each philosopher a separate array because there is no guarantee that a given thread will have read the information before the main thread reassigns a new value. Usually, you'll use a structure, not an array, for the data passed to an individual thread; you have an initialized array of those structures so that each thread gets its own unique control information.
Is there any way you can give an example of this?
Somewhat like this. The key point is the array of struct Info, each of which is separately initialized (using a C99 compound literal) and a different element of the array is passed to each thread so that it gets its own data, rather than trying to share data with other threads.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
struct Info
{
int number;
int turns;
int diner;
};
enum { MAX_PHILOSOPHERS = 10 };
enum { MAX_TURNS = 99 };
static sem_t mutex;
static sem_t S[MAX_PHILOSOPHERS];
static void *philosopher(void *arg_l);
int main(void)
{
int A, B;
printf("How many philosophers? How many turns? ");
fflush(stdout);
if (scanf("%d %d", &A, &B) != 2)
{
fprintf(stderr, "Failed to read input\n");
return 1;
}
if (A < 2)
fprintf(stderr, "You specified too few philosophers (%d)\n", A);
if (A > MAX_PHILOSOPHERS)
fprintf(stderr, "You specified too many philosophers (%d, but the maximum is %d)\n",
A, MAX_PHILOSOPHERS);
if (B < 1)
fprintf(stderr, "You specified too few turns (%d)\n", B);
if (B > MAX_TURNS)
fprintf(stderr, "You specified too many turns (%d, but the maximum is %d)\n",
B, MAX_TURNS);
if (A < 2 || A > MAX_PHILOSOPHERS || B < 1 || B > MAX_TURNS)
return 1;
printf("You have %d philosophers who get %d turns each\n", A, B);
/* This assignment could be in the thread creation loop before pthread_create() */
/* Or in the loop that uses sem_init() */
struct Info info[A];
for (int i = 0; i < A; i++)
info[i] = (struct Info){ A, B, i};
sem_init(&mutex, 0, 1);
for (int i = 0; i < A; i++)
sem_init(&S[i], 0, 0);
pthread_t thread_id[A];
for (int i = 0; i < A; i++)
{
pthread_create(&thread_id[i], NULL, philosopher, &info[i]);
printf("Philosopher %d is thinking\n", i + 1);
}
for (int i = 0; i < A; i++)
pthread_join(thread_id[i], NULL);
printf("Dinner is over\n");
return 0;
}
static void *philosopher(void *arg_l)
{
struct Info *info = arg_l;
printf("N = %d, T = %d, I = %d\n", info->number, info->turns, info->diner);
/* ...do dining stuff; remember to share nicely!... */
return 0;
}
The #pragma allows the code to compile on macOS Sierra, which doesn't have working versions of the <semaphore.h> functions — they just return an error indication and set errno to ENOSYS (function not implemented).
This code should check the return value of the pthread functions and the semaphore operations too — it is being lazy not to do so.
I got this code from an advanced Linux programming book. When I try to execute the code under Linux 64bit environment the value of the which_prime variable gets corrupted (changes to 0) after pthread_join() function call.
In this example why the value of which_prime gets corrupted after running pthread_join?
In general can we use the 4th argument passed to pthread_create function safely inside main even if we call other functions like pthread_join()?
#include <pthread.h>
#include <stdio.h>
/* Compute successive prime numbers (very inefficiently). Return the
Nth prime number, where N is the value pointed to by *ARG. */
void* compute_prime (void* arg)
{
int candidate = 2;
int n = *((int*) arg);
while (1) {
int factor;
int is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor < candidate; ++factor)
if (candidate % factor == 0) {
is_prime = 0;
break;
}
/* Is this the prime number we’re looking for? */
if (is_prime) {
if (--n == 0)
/* Return the desired prime number as the thread return value. */
return (void*) candidate;
}
++candidate;
}
return NULL;
}
int main ()
{
pthread_t thread;
int which_prime = 5000;
int prime;
/* Start the computing thread, up to the 5,000th prime number. */
pthread_create (&thread, NULL, &compute_prime, &which_prime);
/* Do some other work here... */
/* Wait for the prime number thread to complete, and get the result. */
pthread_join (thread, (void*) &prime);
/* Print the largest prime it computed. */
printf(“The %dth prime number is %d.\n”, which_prime, prime);
return 0;
}
We've arrived at a point in time where it is no longer safe to convert between an int and a pointer. That's because there are 64-bit systems where a pointer is 64-bits, but an int is only 32-bits.
So assuming 32-bit int and 64-bit pointer, here's what's happening in your code. The second argument to pthread_join is a pointer-to-a-pointer. In other words, you should be passing the address of a pointer (the address of a 64-bit value). Instead, you are passing the address of prime (the address of a 32-bit value). When pthread_join writes the result, it overwrites which_prime, because which_prime follows prime in memory.
To fix the problem, you need to avoid converting between ints and pointers. One way to do that is to avoid using the second parameter of pthread_join, as demonstrated by the following code.
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 20
typedef struct
{
int success;
int input;
int output;
} stData;
void *doSomething( void *arg )
{
stData *dataptr = arg;
dataptr->success = 1;
dataptr->output = dataptr->input * 2;
return NULL;
}
int main( void )
{
int i;
pthread_t id[NUM_THREADS];
stData data[NUM_THREADS] = {{0}};
for ( i = 0; i < NUM_THREADS; i++ )
{
data[i].input = i + 1;
pthread_create( &id[i], NULL, doSomething, &data[i] );
}
for ( i = 0; i < NUM_THREADS; i++ )
{
pthread_join( id[i], NULL );
if ( data[i].success )
printf( "thread %2d: input=%2d output=%2d\n", i+1, data[i].input, data[i].output );
else
printf( "thread %2d: failed\n", i+1 );
}
return 0;
}
Here is a block of code that creates a number of threads provided by the user, each thread then generates a random number and calculates its squareroot. I cannot figure out why the threads are getting the same ID, line 64 is the culprit as it is where the threads are being created. I suspect that there is something happening in the loop that is causing the threads to all be generated at the same time.
////////////////////////////////////////////////
//
//
// Zach
//
//
//
//
////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
void *squareroot(void *num1)
{
int *id = (int *)num1;
int incoming = rand()/100;
float *outgoing = (float *)malloc(sizeof(float));
printf("%d \n", *id);
printf("%d\n", incoming);
*outgoing = 5.000;
//Calculate the square root of the number passed to the function
*outgoing = sqrt(incoming);
return outgoing;
}
int main(int argc, char* argv[])//testing funcion
{
srand(time(NULL));
int i, j;
int *temp = (int *)malloc(sizeof(int));
if (argc != 2)
{
printf ("ERROR: Enter a number\n");
return 1;
}
int loop = atoi(argv[1]); //grabbing the integer supplied by user
pthread_t thread_id[loop];
void *exit_status;
float *thread_result;
for(i = 0; i < loop; i++)
{
pthread_create(&thread_id[i], NULL, squareroot, &i);
}
for(j = 0; j < loop; j++)
{
pthread_join(thread_id[j], &exit_status);
thread_result = (float *)exit_status;
printf("%f\n", *thread_result);
}
}
I think what is happening is that your loop finishes creating all the threads (or at least some of them) before any of the threads actually run and extract their unique id.
Because you're passing a pointer to i, when each thread finally gets around to checking its parameter, i is already finished... Or at least partway through. The danger is that multiple threads might see the same value for i. It's even worse that you never copy the value out of that pointer - you always dereference it. That means it might change in the middle of your thread's execution.
What you should do instead is pretend it is a pointer:
pthread_create(&thread_id[i], NULL, squareroot, (void*)i);
And in your thread function:
int id = (int)num1;
This works because the pointer is passed by value. Whatever value you provide is the value that goes into the thread function. Previously it didn't work because you passed a pointer to a value that could change in another thread.
PS: Don't forget to free the result from each thread in your loop at the end. At the moment you're not cleaning up memory that you allocated.