关于面向对象的多线程程序设计的问题~

yebeans 2006-10-16 11:13:03
如果要每个对象产生一个线程,只对对象本身成员进行操作。那么线程间通信应该怎么设计呢?
传递参数的话可不可以传递THIS指针过去操作而没有什么隐患?
MFC的有些类传THIS指针过去操作有的会有问题(为什么呢?),那么自定义的类呢?好象有时候运行的时候会出现访问冲突
...全文
157 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yebeans 2006-10-17
  • 打赏
  • 举报
回复
谢谢,那么对于 自己定义的类(工作线程只是有些I/O操作)直接传THIS指针会不会有什么问题呢
rickerliang 2006-10-17
  • 打赏
  • 举报
回复
附上msdn的解释
As a general rule, a thread can access only MFC objects that it created. This is because temporary and permanent Windows handle maps are kept in thread local storage to help maintain protection from simultaneous access from multiple threads. For example, a worker thread cannot perform a calculation and then call a document's UpdateAllViews member function to have the windows that contain views on the new data modified. This has no effect at all, because the map from CWnd objects to HWNDs is local to the primary thread. This means that one thread might have a mapping from a Windows handle to a C++ object, but another thread might map that same handle to a different C++ object. Changes made in one thread would not be reflected in the other.

There are several ways around this problem. The first is to pass individual handles (such as an HWND) rather than C++ objects to the worker thread. The worker thread then adds these objects to its temporary map by calling the appropriate FromHandle member function. You could also add the object to the thread's permanent map by calling Attach, but this should be done only if you are guaranteed that the object will exist longer than the thread.

Another method is to create new user-defined messages corresponding to the different tasks your worker threads will be performing and post these messages to the application's main window using ::PostMessage. This method of communication is similar to two different applications conversing except that both threads are executing in the same address space.

另外msdn的
TN003: Mapping of Windows Handles to Objects
指出了那些MFC类的对象不能在线程间传递,你可以参考一下
rickerliang 2006-10-17
  • 打赏
  • 举报
回复
用SendMessage或PostMessage对handle进行操作
yebeans 2006-10-17
  • 打赏
  • 举报
回复
ok~谢了
rickerliang 2006-10-17
  • 打赏
  • 举报
回复
自定义类型的,线程间访问的时候同步一下就可以了,没啥问题的

15,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧