Nun, ich versuche, eine Variable in einem Thread verwenden, funktioniert es gut, wenn ich den PThread von der Hauptfunktion aufrufen, aber wenn ich anrufe es aus einer Funktion oder einer Funktion innerhalb einer Klasse, wird die Variable verloren und druckt statt Müll, das ist, warum ich die BedingungPthread Zugriff auf es von einer Klasse, Variablen verloren gehen, wenn direkt funktioniert
if(this->pickup < 7)
so habe ich den Code so minimiert ich es hier posten könnte, weil es alle Beispiele hat Ich sage.
Der Ausgang dieses Code unten:
Access by Class:
Hello, world! <
Access Directly:
Hello, world!, N: 6<
ich wie in Access das gleiche Ergebnis haben möchte direkt in Access von der Klasse, ich will es zur Ausgabe des“N: 6" , weil nach alles wurde definiert. Was fehlt mir hier?
Ich hoffe, ich war klar genug, danke im Voraus.
(By the way, ich bin die pthread-Bibliothek, die für Windows verfügbar ist) so hier ist der Code:
#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
class C {
public:
int pickup;
void *hello()
{
std::cout << "\nHello, world!";
if(this->pickup < 7)
std::cout << ", N: " << this->pickup;
std::cout << "<" << std::endl;
printf("HI");
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
void StartThread(){
C c;
c.pickup = 6;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
}
};
int main() {
C c;
std::cout << "Access by Class: \n";
c.StartThread();
c.pickup = 6;
Sleep(2000);
std::cout << "\nAccess Directly: \n";
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
_getch();
return 0;
}
hm Wie könnte ich das beheben? – Grego
@Grego, aktualisierte Antwort. – hmjd
es noch Müll gedruckt, ging es Hallo, Welt !, N: -17891602 – Grego