pthread argumente



  • hi ihr,

    weiss jemand, wie ich einem thread möglichst einfach beliebige argumente mitgeben kann?
    also, beispiel:

    #include <pthread.h>
    #include <iostream>
    using namespace std;
    
    void *funktion( void *a){
    cout<<"bla"<<endl;
    pthread_exit(NULL);
    }
    
    int main(){
    int x=1;
    pthread_t th1;
    pthread_create(&th1, NULL, funktion, &x);
    funktion((void*)x);
    return 0;
    }
    

    sollte zweimal "bla" ausgeben.
    soweit so gut, ich würde aber gerne eine sinnvolle funktion haben(die von einem thread ausgeführt wird), wenigstens eine, der ich strings übergeben kann und integers und so, weiss jemand, wie ich das machen kann? oder z.b. auch auf die eins zugreifen kann, die ja eigtl in x drin ist und die ausgeben kann?



  • Hallo

    Das was du da als Adresse von x übergibst, bekommst du aus dem Parameter wieder raus-casten.

    #include <pthread.h>
    #include <iostream>
    using namespace std;
    
    void *funktion( void *a){
    int* value = reinterpret_cast<int*>(a);
    cout<<*value<<endl;
    pthread_exit(NULL);
    }
    
    int main(){
    int x=1;
    pthread_t th1;
    pthread_create(&th1, NULL, funktion, &x);
    funktion((void*)x);
    return 0;
    }
    

    Äquivalent für jeden andern Typ

    bis bald
    akari



  • hm, danke askari,

    das prob ist jetzt nur noch, dass ich da nen speicherzugriffsfehler bekomm.
    thread 1 machts gut, thread zwei nicht.

    #include <pthread.h>
    #include <iostream>
    using namespace std;
    
    void *funktion( void *a){
    int* value = reinterpret_cast<int*>(a);
    cout<<*value<<endl;
    //pthread_exit(NULL);
    }
    
    int main(){
    int x=1;
    pthread_t th1;
    pthread_create(&th1, NULL, funktion, &x);
    pthread_join(th1, NULL);
    funktion((void*)x);
    return 0;
    }
    

    ausgabe:

    linux-cctu:~/prgversuche> ./a.out
    1
    Speicherzugriffsfehler
    

    was natürlich irgenwie doof ist.



  • myggel schrieb:

    [...]
    funktion((void*)x);
    return 0;
    }
    

    ausgabe:

    Sicher, dass du nicht funktion((void*)&x); meintest?



  • uhmmmm, joa, das ist glaub ganz vernünftig, das mal zu testen. ähm.

    danke.


Anmelden zum Antworten