在c++中向线程传递对象
Passing an object to a thread in C++
我有一个项目,它创建一个存储在头文件中的类的对象。我需要把这个对象从主函数传递给线程。
目前我使用hChatThread = CreateThread(NULL,0,ChatFunc,"1",0,&dwChatThreadId);
作为创建线程的一种方式,似乎我无法改变被调用的函数只能将LPVOID
作为类型的事实。如果我能改变这一点,我就可以像这样传递对象作为参数:hChatThread = CreateThread(NULL,0,ChatFunc,myObject,0,&dwChatThreadId);
但这似乎几乎是不可能的。
任何想法?
线程:DWORD WINAPI ChatFunc(LPVOID randparam)
{
ServerMain(myObject); //need to pass object again here to be used in other functions
return 0;
}
主:int main(int argc, char *argv[])
{
myObject w;
w.exec();
hChatThread = CreateThread(NULL,0,ChatFunc,"1",0,&dwChatThreadId);
return 0;
}
您可以使用LPVOID lpParameter
传递指向对象的指针,然后将其强制转换回来。像这样:
int main(int argc, char *argv[])
{
myObject w;
w.exec();
hChatThread = CreateThread(NULL,0,ChatFunc,&w,0,&dwChatThreadId);
// wait for the thread to terminate,
// otherwise w might get destroyed while the thread
// is still using it (see comments from @MartinJames)
return 0;
}
DWORD WINAPI ChatFunc(LPVOID param)
{
myObject* p = static_cast<myObject*>(param);
ServerMain(p); //need to pass object again here to be used in other functions
return 0;
}
最简单的方法是在头文件中使该Object成为全局对象,并且假定您包含了以下代码:
#include "headerFilesName.h"
main函数所在文件中的。然后用main函数在文件中声明另一个对象并将其值
传递给它headerFileName myNewObject;
使用头文件类的这个对象,您应该能够访问最初创建的其他对象。
只有一个灵活的解决方案-动态分配'w'与operator new,传递指针到CreateThread,将其转换回线程函数,当/如果线程函数退出/返回,对象实例不再需要,删除它。
所有其他的解决方案要么工作不可靠,有混乱的全局或不灵活。
相关文章:
- 即发即弃 std::线程对象清理自身
- C++:处理线程本地对象销毁
- 结束另一个线程中使用的对象的生存期
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 线程调用的函数对对象删除是否安全?
- 将对象传递给多线程对象 Qt
- asio 链对象线程安全吗?
- 如何初始化大线程本地对象?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 当只有一个线程主要使用该对象而其他线程很少使用它时,如何最小化该对象的互斥锁锁定?
- 如何将对象从类线程传递到帖子?
- 将抽象对象从主线程发送到其他线程
- 在 While 循环中重用对象的多线程
- 本地静态函数对象线程安全的初始化
- 对于 c++11 之前的编译器,返回本地静态对象线程是否安全
- 从一个对象线程中使用 const 方法是否安全
- C++流对象线程安全
- 使STL对象线程安全的标准方法
- QT多线程和移动对象线程创建后