Múltiples argumentos a la función llamada por pthread create()?
Necesito pasar varios argumentos a una función que me gustaría llamar en un subproceso separado. He leído que la forma típica de hacer esto es definir una estructura, pasar un puntero a la función y desreferenciarla para los argumentos. Sin embargo, no puedo hacer que esto funcione:
#include <stdio.h>
#include <pthread.h>
struct arg_struct {
int arg1;
int arg2;
};
void *print_the_arguments(void *arguments)
{
struct arg_struct *args = (struct arg_struct *)args;
printf("%d\n", args -> arg1);
printf("%d\n", args -> arg2);
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t some_thread;
struct arg_struct args;
args.arg1 = 5;
args.arg2 = 7;
if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
printf("Uh-oh!\n");
return -1;
}
return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
La salida para esto debe ser:
5
7
Pero cuando lo corro realmente obtengo:
141921115
-1947974263
¿Alguien sabe lo que estoy haciendo mal?
5 answers
Porque dices
struct arg_struct *args = (struct arg_struct *)args;
En lugar de
struct arg_struct *args = arguments;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-30 01:06:08
Use
struct arg_struct *args = (struct arg_struct *)arguments;
En lugar de
struct arg_struct *args = (struct arg_struct *)args;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-15 10:46:10
main()
tiene sus propias variables de hilo y pila. asignar memoria para 'args' en el montón o hacerlo global:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
Luego, por supuesto, cambie las referencias de args->arg1
a args.arg1
etc..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 07:18:44
Uso:
struct arg_struct *args = malloc(sizeof(struct arg_struct));
Y pasar estos argumentos como este:
pthread_create(&tr, NULL, print_the_arguments, (void *)args);
No te olvides de args gratis! ;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-06 06:49:33
Los argumentos de print_the_arguments son argumentos, por lo que debe usar:
struct arg_struct *args = (struct arg_struct *)arguments.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 08:17:18