Probleme mit pthread
-
Hallo Leute!
Habe ein Programm das eine gewisse Anzahl von Threads erzeugt und dann pro Thread einen bestimmten Text ausgibt.
Mein Problem ist, dass ich immer ein Segmentation fault bekomme.
Vielleicht kann mir jemand von euch weiterhelfen.Hier mal der Code.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <pthread.h> void *print_thread(); /** * main program */ int main(int argc, char **argv) { int n; //n threads int i; int res; // for errorhandling /* reads the amount of threads */ printf("Please insert number of threads : "); scanf("%d",&n); /* memory allocation */ pthread_t tid[n]; printf("Number of Threads : %d \n", n); for(i=0; i<n; i++) { //creating thread res = pthread_create(&(tid[i]) , NULL, print_thread(), NULL); if(res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } } for(i=0; i<n; i++) { //waiting for threads pthread_join(tid[i],NULL); } return EXIT_SUCCESS; } /* Function which prints 'Hello World' with a delay of 1 second */ void *print_thread(void *var) { pthread_t tid; tid = pthread_self(); printf("Thread: %d Timestamp: %d: Hello World\n", (int) tid, (int) time(NULL)); sleep(1); return EXIT_SUCCESS; }
Gruß
Christian
-
1. printf ist nicht threadsafe. Da muss ein mutex drum herum.
2. pthread_t tid[n]; funktioniert eher nicht: pthread_t * tid = malloc(sizeof(pthread_t) * n);
-
Hallo!
Versuche es mal so:
res = pthread_create(&tid[i], NULL, print_thread(), NULL);
Und in der print_thread() würde ich statt des return ein
pthread_exit(NULL);
benutzen. Es geht aber wohl beides.
Ansonsten...... geht das so mit dem dynamischen Array (tid[n])?
Denke eher so:[...] printf("Please insert number of threads : "); scanf("%d",&n); tid = (pthread_t *)malloc(n * sizeof(pthread_t)); if( tid == NULL ) { printf("Fehler bei malloc()!\n"); return EXIT_FAILURE; } pthread_t tid[n]; for(i=0; i<n; i++) { //creating thread [...]
Aber keine Garantie
Gruß
Thorsten
-
Ponto schrieb:
1. printf ist nicht threadsafe. Da muss ein mutex drum herum.
Echt nicht? Bei mir funktioniert das mit dem printf immer wunderbar und mein aktuelles Projekt benutzt fast ausschließlich Threads.
-
Hi!
Danke für eure Antworten.
Hab den Fehler gefunden.
res = pthread_create(&tid[i], NULL, print_thread(), NULL);
wird zu
res = pthread_create(&tid[i], NULL, print_thread, NULL);
Die Fuktionsklammer waren im Weg.
Werd aber eure Vorschläge auch mal ausprobieren.
Vorallem die dynamische Speichergenerierung ist für diesen Fall sicher die bessere Wahl.
Danke nochmal
Christian