Zuerst mich durch die Veröffentlichung des Codes starten lassen:Segmentation Fault auf Pthread Malloc
#include <pthread.h>
#include<stdlib.h>
//64 BITS -ALL 32 bit Arch
//32 BIT - UNIX 64 bit arch
//64 BIT - WINDOWS 64 bit arch
long long sum = 0;
static enum turn
{
PING,
PONG
}def;
struct threads_util
{
pthread_t *t_id;
pthread_attr_t *attr;
void (*init_attr)(pthread_attr_t *);
};
void init_attr_fn(pthread_attr_t *attr)
{
pthread_attr_init(&attr);
}
void* sum_runner(void* arg)
{
long long* limit_ptr = (long long *) arg;
long long limit = *limit_ptr;//Derefrencing
for(long long i=0; i<=limit; i++)
sum += i;
printf("Sum is %lld \n", sum);
pthread_exit(0);
}
void ping()
{
puts("Ping");
def = PONG;
}
void pong()
{
puts("Pong");
def = PING;
}
pthread_t * all_thread(pthread_t *t_id)
{
t_id = malloc(sizeof(pthread_t));
return t_id;
}
int main(int argc, char **argv)
{
if(argc<2)
{
puts("Usage ./objFile <num 1> <num 2> .. <num n>");
exit(1);
}
int args = argc-1;
long long limit = atoll(argv[1]);
def = PING;
struct threads_util *threads[args];
for (int i=0; i<args; i++)
threads[i]->t_id = all_thread(threads[i]->t_id);
puts("In");
for(int i=0; i<args; i++)
{
threads[i]->init_attr = init_attr_fn;
threads[i]->init_attr(threads[i]->attr);
pthread_create(threads[i]->t_id,threads[i]->attr,sum_runner,&limit);
}
//Begin -Main Functions
for(int i=0; i<= 10; i++)
{
if(def == PING)
ping();
else if(def == PONG)
pong();
else
puts("UNKOWN PI-PO");
}
//End - Main Functions
for(int i=0; i<args; i++)
{
pthread_join(threads[i]->t_id,NULL);
}
}
Sie können sehen, ich habe eine puts („In“), in der Hauptfunktion, kurz nach der for-Schleife, wenn ich rufe all_thread args mal. Nun, die Funktion argc mal mit der for-Schleife entsprechend meiner Debugging-Fähigkeiten aufrufen, ist das Problem. Und bevor wir die Allokations-Strategie gemacht haben, hatte ich ein Problem beim Aufruf der Thread-Funktion, was natürlich zu einem Segmentierungsfehler führte. threads[i]->init_attr(threads[i]->attr);
. Hilfe würde sehr geschätzt werden.
Ok im dieses Problem passieren .. Können Sie auf dem Chat http://chat.stackoverflow.com/rooms/54304/c gehen? Im Moment habe ich ein Problem mit der Initialisierung der Attribute: threads [i] -> init_attr (threads [i] -> attr); – amanuel2
Was ist 'pthread_attr_init'? – 4386427
Scheint, dass' threads [i] -> attr' nicht initialisiert ist - vielleicht solltest du es einfach auf 'NULL' initialisieren – 4386427