有一堂课。可以将参数传递给流。在下面的示例中,我在那里传递了一个字符串并将其输出到控制台。但问题来了,我的线程类实例不存在。也就是说,当然,我可以在线程中创建该类的另一个实例并使用它,但我想以某种方式将我使用的实例转移到线程main()
。有必要访问类对象并在某些条件下更改它们。例如,更改线程中的值bool checked
并执行method1()
.
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class SomeClass {
public:
SomeClass(int value) {
this->value = value;
checked = false;
}
~SomeClass() {
cout << "The end" << endl;
}
void method1() {
cout << value;
checked = true;
}
private:
int value;
bool checked;
};
DWORD WINAPI MyThread(LPVOID param) {
cout << ((string*)param)[0] << endl;
system("pause");
return 0;
}
int main() {
SomeClass SC(5);
SC.method1();
DWORD thID;
HANDLE handle;
string str = "hello";
handle = CreateThread(NULL, NULL, MyThread, &str, NULL, &thID);
system("pause");
return 0;
}
有一个这样的假设:(它有效,但我正在使用同一个实例?)
handle = CreateThread(NULL, NULL, MyThread, &SC, NULL, &thID);
和
DWORD WINAPI MyThread(LPVOID param) {
SomeClass SC2 = ((SomeClass*)param)[0];
SC2.method1();
//cout << ((string*)param)[0] << endl;
return 0;
}
例如,可以这样做:
你有正确的想法,但
SomeClass SC2 = ((SomeClass*)param)[0];
字符串中没有数组,你只需要转换void*
为SomeClass*
:SomeClass* SC2 = reinterpret_cast<SomeClass*>(param);
好吧,您需要注意同步,在我的示例中它是一个互斥锁,在 winapi 中这些是关键部分。