Reputation: 1671
I'm approaching C programming with threads and I can't get this program to work properly. Basically there's a vector with k elements, n threads and each thread has to calculate the max on its k/n elements.
My code is (please note it's not the whole code):
// Struct code used later
struct maxStruct
{
double *vettore;
int dimensione;
};
// Gathering data input from user
[ . . . ]
vector = (double *) malloc (dimensione * sizeof(double));
pid_thread = (int *) malloc (numero_thread * sizeof(int));
thread = (pthread_t *) malloc (numero_thread * sizeof(pthread_t));
// Generating the vector
[ . . . ]
for (i = 0; i < numero_thread; i++)
{
e = generaStruct(i, vettore, dimensione, numero_thread);
if (status = pthread_create(&thread[i], NULL, calcolaMassimo, (void *) e))
{
pthread_perror("pthread_join", status);
exit(1);
}
}
//Note that the function doesn't calculate the max, I've coded it in this way
//in order to see whether it was being called by each thread and apparently it is not.
void *calcolaMassimo(void * e)
{
printf("Sono chiamata!!\n");
struct maxStruct *sottoVettore = e;
printf("Dimensione: %d\n", ((*sottoVettore).dimensione));
}
Apparently this function is not being called by each thread and I can't figure out why. Will you please help me solve this issue?
Upvotes: 1
Views: 161
Reputation: 4615
Firstly, a minor nit pick, the idiomatic way to write (*sottoVettore).dimensione)
is sottoVettore->dimensione
.
The process containing all of threads will exit when main()
exits. I know you said you're joining in you're actual code so that should not be an issue but if you're not joining in the test code then that could be an issue.
It is also possible that the issue is not that the code in each thread isn't executing, but that the statements aren't actually reaching stdout
. You might want to try a fflush(stdout)
at the end of calcolaMassimo
and see if that changes things.
Upvotes: 2