从 dll 中的静态成员线程化
我在处理 A 类中的线程时遇到问题,例如,A 类是 dll 中 B 类的静态成员。我正在使用 Visual Studio 9 和 boost 1.40。请考虑以下代码:
mylib.h:
#include <boost/thread.hpp>
#include <windows.h>
#ifdef FOO_STATIC
#define FOO_API
#else
#ifdef FOO_EXPORT
#define FOO_API __declspec(dllexport)
#else
#define FOO_API __declspec(dllimport)
#endif
#endif
class FOO_API foo{
boost::thread* thrd;
public:
foo();
~foo();
void do_work();
};
class FOO_API bar{
static foo f;
public:
static foo& instance();
};
mylib.cpp:
#include "mylib.h"
foo::foo()
{
thrd = new boost::thread(boost::bind(&foo::do_work,this));
}
foo::~foo(){
thrd->join();
delete thrd;
}
void foo::do_work(){
printf("doing some works\n");
}
foo& bar::instance(){return f;}
foo bar::f;
在可执行应用程序中,我有:
main.cpp:
#include "mylib.h"
void main(){
bar::instance();
}
如果我将 mylib 静态链接到可执行应用程序,它会打印出“做一些工作”,而如果我链接它动态地(dll),它什么也不做。
我真的很感谢任何帮助。
I have a problem lunching a thread within a class A for example where the class A is a static member of class B with in a dll. I am using Visual Studio 9 and boost 1.40. Please consider the following code:
mylib.h:
#include <boost/thread.hpp>
#include <windows.h>
#ifdef FOO_STATIC
#define FOO_API
#else
#ifdef FOO_EXPORT
#define FOO_API __declspec(dllexport)
#else
#define FOO_API __declspec(dllimport)
#endif
#endif
class FOO_API foo{
boost::thread* thrd;
public:
foo();
~foo();
void do_work();
};
class FOO_API bar{
static foo f;
public:
static foo& instance();
};
mylib.cpp:
#include "mylib.h"
foo::foo()
{
thrd = new boost::thread(boost::bind(&foo::do_work,this));
}
foo::~foo(){
thrd->join();
delete thrd;
}
void foo::do_work(){
printf("doing some works\n");
}
foo& bar::instance(){return f;}
foo bar::f;
in the executable application, I have:
main.cpp:
#include "mylib.h"
void main(){
bar::instance();
}
If I link mylib statically to the executable app, It prints out "doing some works", while if I link it dynamically (dll), it does nothing.
I really appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的程序可能会在线程完成之前退出。您可以尝试在
bar::instance()
调用之后等待,或者在main
中加入线程。其他可以尝试的方法是在 printf 调用之后刷新标准输出。Your program could be exiting before the thread completes. You might try waiting after the
bar::instance()
call, or joining the thread inmain
. Something else to try would be to flush stdout after theprintf
call.来自 MSDN 文档:
(*) 这些限制包括与线程的通信。
最好将全局变量设为指针,并在专用回调例程中构造和释放对象。
另请参阅这个很有帮助的答案。
From the MSDN documentation:
(*) The restrictions include communicating with threads.
It's best to make the global variable a pointer, and construct and release the object in dedicated callback routines.
See also this helpful SO answer.