Reputation: 63
i'd like to create threads
int joueur=3; // in my case it is in a "for" loop
jouer(joueur);
I used this syntax
I have tried with this:
int *joueur = malloc(sizeof(*joueur));
//if (joueur == NULL)
//doNotStartTheThread_ProblemAllocatingMemory();
pthread_create(&threads[joueur], NULL, jouer, (int *) joueur);
jouer function
void jouer(int joueur)
{
while(but_trouve==0)
{
pthread_mutex_lock (&mutex);
for(joueur=0;joueur<nombre_joueurs;joueur++) if(labyrinthe[joueur_ligne[joueur]][(joueur_colonne[joueur])%4]="b") but_trouve=1;
if (but_trouve==1) break; // si un joueur a trouve le but on termine la partie
deplacer(joueur);
// pthread_cond_signal (&condition); /* On délivre le signal : condition remplie */
pthread_mutex_unlock (&mutex); // Fin de la zone protegee
affiche();
}
pthread_exit(NULL);
}
But i have this message now.
warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
pthread_create(&threads[threads[nombre_joueurs]], NULL, jouer, (int *) joueur);
In file included from /home/nouha/test.c:4:0:
/usr/include/pthread.h:244:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(int)’
extern int pthread_create (pthread_t *__restrict __newthread,
, Thank you for reading,
Upvotes: 1
Views: 1320
Reputation: 63
Here's the correct answer:
void *jouer(void *arg);
int joueur=0;
for(joueur=0;joueur<nombre_joueurs;joueur++)
{
affiche();
int *joueur = malloc(sizeof(*joueur));
pthread_create(&threads[threads[nombre_joueurs]], NULL, jouer, (int *) joueur);
}
Upvotes: 1
Reputation: 53016
You are passing the value of the variable, it expects the address.
You can't pass joueur
's address to pthread_create()
as the data parameter because it's a local variable and it will be deallocated when the function returns, which might happen before the thread finishes working.
I would suggest
int *joueur = malloc(sizeof(*joueur));
if (joueur == NULL)
doNotStartTheThread_ProblemAllocatingMemory();
pthread_create(&threads[joueur], NULL, jouer, (void *) joueur);
note that above, the type of joueur
is int *
, in your example it's int *
you can't pass that to the pthread_create()
function just by casting it to void *
because it's interpreted as an address, and I doubt that 3
will be a valid one.
Don't forget to free joueur
when the thread is done working with the poitner, because you can't free it before or the same problem will happen.
Upvotes: 2