1

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.

Anthony Graglia
  • 5,355
  • 5
  • 46
  • 75
Arash
  • 39
  • 3

2 Answers2

0

Your program could be exiting before the thread completes. You might try waiting after the bar::instance() call, or joining the thread in main. Something else to try would be to flush stdout after the printf call.

Nathan Ernst
  • 4,540
  • 25
  • 38
  • You are right. I have to either wait after bar::instance() or join the thread in main. – Arash Dec 22 '10 at 20:39
  • So my question is if there is an static object who creates a thread or more internally through shared_ptr for example, what would be the proper way to exit the application since I have no means to join the thread or wait for them to get completed inside the main app. – Arash Dec 22 '10 at 20:56
0

From the MSDN documentation:

If your DLL is linked with the C run-time library (CRT), the entry point provided by the CRT calls the constructors and destructors for global and static C++ objects. Therefore, these restrictions (*) for DllMain also apply to constructors and destructors and any code that is called from them.

(*) 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.

Community
  • 1
  • 1
Amnon
  • 7,652
  • 2
  • 26
  • 34