Sto provando a scrivere un programma multi-thread, il numero di thread basato sull'input da riga di comando, e quindi non posso hardcriptare i thread pre-dichiarati. È un modo valido per farlo?Come generare n thread?
int threads = 5; // (dynamic, not hard-coded)
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
pthread_t foobar;
thread[i] = foobar; // will this cause a conflict?
}
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
Ecco il mio risultato di modifiche suggerite di seguito. Sembra funzionare bene.
int threads = 5;
int i;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
// pthread_join(thread[i], NULL); // don't actually want this here :)
}
sleep(1); // main() will probably finish before your threads do,
free(thread); // so we'll sleep for illustrative purposes
non si può semplicemente assegnare un intero ad una stringa nel bit 'int threads = argv [3]'. Devi usare 'atoi' o sscanf –
grazie, hai ragione. fisso. –
Bene, con 'pthread_join()' è dove si trova, devi creare il thread, e quindi attendere che finisca prima di spawnare il prossimo. Quindi in effetti sarai quasi single-threaded qui :) –