;I am trying to use the pthread.h library to find the minimum number from an array. I am having trouble getting the code to compile and am unfamiliar with how to use pointers properly to make it work.
#include <iostream>
#include <pthread.h>
using namespace std;
int *min;
int *max;
double *average;
int n;
void* minimum(void* a){
int size = n;
int* array = (int*) a;
int tempmin = array[0];
for(int i=0; i<size; i++){
if(array[i] < tempmin){
tempmin = array[i];
}
}
return NULL;
}
int main(){
int in;
cout << "How many numbers would you like to enter?" << endl;
cin >> n;
int numbers[n];
for(int i=0; i<n; i++){
cout << "enter number " << i+1 << endl;
cin >> in;
numbers[i] = in;
}
pthread_t thread1;
int iret1
pthread_create(&thread1, NULL, &minimum, (void*)numbers);
}
I am assuming this is just an exercise, since there are better ways to achieve what you want. Please read this link . So here are some points to watch for:
1 - After pthread_create, you should call pthread_join to wait for it to complete and also to release its resources (you could also create a detached thread). You also need to pass the array to the thread as an argument:
pthread_create(&thread1, NULL, &minimum, (void*)numbers);
pthread_join(thread1, NULL);
2 - The thread function receives a void*, so you need to cast it to whatever the argument really is:
void* minimum(void* a){
int size = n;
int* array = (int*) a;
int tempmin = array[0];
for(int i=0; i<size; i++){
if(array[i] < tempmin){
tempmin = array[i];
}
}
return NULL;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.