pthread - komischer fehler
-
hi,
ich probier mich gerade an pthreads und bekomm ein merkwürdigen fehler bei dem code:
#include <stdio.h> #include <pthread.h> void cleanup( void *arg ); void *loop( void *arg ); void *mainthread( void *arg ); int main( void ) { pthread_t schleife; pthread_t mthread; pthread_create( &schleife, NULL, loop, NULL ); pthread_create( &mthread, NULL, mainthread, (void*) &schleife ); pthread_join( schleife, NULL ); pthread_join( mthread, NULL ); printf( "hallo welt\n" ); return 0; } void cleanup( void *arg ) { printf( "thread wurde beendet\n" ); } void *loop( void *arg ) { pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL ) ; pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, NULL ); pthread_cleanup_push( cleanup, NULL ); return NULL; } void *mainthread( void *arg ) { pthread_t *thread = (pthread_t*) arg; pthread_cancel( *thread ); return NULL; }
Ausgabe:
gcc -Wall thread.c -o thread -lpthread thread.c: In Funktion »loop«: thread.c:34: Fehler: expected »while« before »void« thread.c:40: Fehler: expected declaration or statement at end of input thread.c:40: Fehler: expected declaration or statement at end of input
was für ein while bitte meint der? hat der vielleicht die thread.c datei noch falsch im speicher, denn ich hatte mal ein while drin aber das hab ich rausgemacht?
mfg blan
-
pthread_cleanup_push ist ein Makro, welches eine do { } while Schleife öffnet. Das Gegenstück ist pthread_cleanup_pop, welches die Schleife wieder schließt. Du musst also den pthread_cleanup_pop in demselben Scope wie den pthread_cleanup_push setzen.
-
LordJaxom schrieb:
pthread_cleanup_push ist ein Makro, welches eine do { } while Schleife öffnet. Das Gegenstück ist pthread_cleanup_pop, welches die Schleife wieder schließt. Du musst also den pthread_cleanup_pop in demselben Scope wie den pthread_cleanup_push setzen.
okay, das funktioniert dann wohl soweit. aber entweder ich hab was falsch verstanden oder es funktioniert nicht richtig. ich will ja ein thread haben der eine bestimmte funktion aufruft (in meinem fall ist das cleanup(...)) wenn er gecancelt wird. wie muss dann der code aussehen?
mein code ist folgender:
void *loop( void *arg ) { pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL ) ; pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, NULL ); pthread_cleanup_push( cleanup, NULL ); pthread_cleanup_pop( 1 ); pthread_cleanup_push( cleanup, NULL ); pthread_cleanup_pop( 1 ); while( 1 ) { } return NULL; }
jetzt wird die funktion gleich aufgerufen egal ob ich cancele oder nicht. wenn ich execute auf 0 setzte geht garnichts. wo muss ich also die pthread_cleanup_* funktionen hinbauen?
edit: okay scheinbar funktioniert das so:
pthread_cleanup_push( cleanup, NULL ); while( 1 ) { } pthread_cleanup_pop( 1 );
bis jetzt funktioniert das so wie ich es mir wünsche - ist das ok so?
mfg blan