Is it possible to bind() *this to class member function to make a callback to C API - c++

Is there a way to use boost or std bind() so I could use a result as a callback in C API?
Here's sample code I use:
#include <boost/function.hpp>
#include <boost/bind/bind.hpp>
typedef void (*CallbackType)();
void CStyleFunction(CallbackType functionPointer)
{
functionPointer();
}
class Class_w_callback
{
public:
Class_w_callback()
{
//This would not work
CStyleFunction(boost::bind(&Class_w_callback::Callback, this));
}
void Callback(){std::cout<<"I got here!\n";};
};
Thanks!

No, there is no way to do that. The problem is that a C function pointer is fundamentally nothing more than an instruction address: "go to this address, and execute the instructions you find". Any state you want to bring into the function has to either be global, or passed as parameters.
That is why most C callback APIs have a "context" parameter, typically a void pointer, that you can pass in, and just serves to allow you to pass in the data you need.

You cannot do this in portable C++. However, there are libraries out there that enable creation of C functions that resemble closures. These libraries include assembly code in their implementation and require manual porting to new platforms, but if they support architectures you care about, they work fine.
For example, using the trampoline library by Bruno Haible, you would write the code like this:
extern "C" {
#include <trampoline.h>
}
#include <iostream>
typedef int (*callback_type)();
class CallbackDemo {
static CallbackDemo* saved_this;
public:
callback_type make_callback() {
return reinterpret_cast<callback_type>(
alloc_trampoline(invoke, &saved_this, this));
}
void free_callback(callback_type cb) {
free_trampoline(reinterpret_cast<int (*)(...)>(cb));
}
void target(){
std::cout << "I got here, " << this << '\n';
};
static int invoke(...) {
CallbackDemo& me = *saved_this;
me.target();
return 0;
}
};
CallbackDemo *CallbackDemo::saved_this;
int main() {
CallbackDemo x1, x2;
callback_type cb1 = x1.make_callback();
callback_type cb2 = x2.make_callback();
cb1();
cb2();
}
Note that, despite the use of a static member, the trampolines created by alloc_trampoline are reentrant: when the returned callback is invoked, it first copies the pointer to the designated address, and then invokes the original function with original arguments. If the code must also be thread-safe, saved_this should be made thread-local.

This won't work.
The problem is that bind returns a functor, that is a C++ class with an operator() member function. This will not bind to a C function pointer. What you need is a static or non-member function that stores the this pointer in a global or static variable. Granted, finding the right this pointer for the current callback might be a non-trivial task.

Globals
As mentioned by the others, you need a global (a static member is a global hidden as a variable member) and of course if you need multiple objects to make use of different parameters in said callback, it won't work.
Context Parameters in Callback
A C library may offer a void * or some similar context. In that case use that feature.
For example, the ffmpeg library supports a callback to read data which is defined like so:
int(*read_packet)(void *opaque, uint8_t *buf, int buf_size);
The opaque parameter can be set to this. Within your callback, just cast it back to your type (name of your class).
Library Context Parameter in Calback
A C library may call your callback with its object (struct pointer). Say you have a library named example which offers a type named example_t and defines callbacks like this:
callback(example_t *e, int param);
Then you may be able to place your context (a.k.a. this pointer) in that example_t structure and retrieve it back out in your callback.
Serial Calls
Assuming you have only one thread using that specific C library and that the callback can only be triggered when you call a function in the library (i.e. you do not get events triggered at some random point in time,) you could still use a global variable. What you have to do is save your current object in the global before each call. Something like this:
object_i_am_working_with = this;
make_a_call_to_that_library();
This way, inside the callback you can always access the object_i_am_working_with pointer. This does not work in a multithreaded application or when the library automatically generates events in the background (i.e. a key press, a packet from the network, a timer, etc.)
One Thread Per Object (since C++11)
This is an interesting solution in a multi-threaded environment. When none of the previous solutions are available to you, you may be able to resolve the problem using threads.
In C++11, there is a new special specifier named thread_local. In the old days, you had to handle that by hand which would be specific to each thread implementation... now you can just do this:
thread_local Class_w_callback * callback_context = nullptr;
Then when in your callback you can use the callback_context as the pointer back to your Class_w_callback class.
This, of course, means you need to create one thread per object you create. This may not be feasible in your environment. In my case, I have components which are all running their own loop and thus each have their own thread_local environment.
Note that if the library automatically generates events you probably can't do that either.
Old Way with Threads (And C solution)
As I mentioned above, in the old days you would have to manage the local thread environment yourself. With pthread (Linux based), you have the thread specific data accessed through pthread_getspecific():
void *pthread_getspecific(pthread_key_t key);
int pthread_setspecific(pthread_key_t key, const void *value);
This makes use of dynamically allocated memory. This is probably how the thread_local is implemented in g++ under Linux.
Under MS-Windows, you probably would use the TlsAlloc function.

Related

C++ Use a class non-static method as a function pointer callback in freeRTOS xTimerCreate

I am trying to use marvinroger/async-mqtt-client that in the provided examples is used together with freertos timers that use a callback that gets invoked whenever the timer expire. The full example is here.
I wanted to create a singleton class to enclose all the connection managing part and just expose the constructor (through a getInstance) and a begin function that other than setting the callbacks, creates the timers for reconnection.
The class looks like (I simplified by removing useless parts):
class MqttManager : public Singleton<MqttManager> {
public:
virtual ~MqttManager() = default;
void begin();
protected:
MqttManager();
void connectToMqtt(TimerHandle_t xTimer);
void WiFiEvent(WiFiEvent_t event);
void onConnect(bool sessionPresent);
std::unique_ptr<AsyncMqttClient> client;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
};
While my issue is when I try to pass the connectToMqtt callback to the timer.
MqttManager::MqttManager() {
this->client = std::unique_ptr<AsyncMqttClient>(new AsyncMqttClient());
// use bind to use a class non-static method as a callback
// (works fine for mqtt callbacks and wifi callback)
this->client->onConnect(std::bind(&MqttManager::onConnect, this, std::placeholders::_1));
WiFi.onEvent(std::bind(&MqttManager::WiFiEvent, this, std::placeholders::_1));
// Here it fails
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)nullptr, &MqttManager::connectToMqtt, this, std::placeholders::_1);
The error is:
cannot convert 'void (MqttManager::)(TimerHandle_t) {aka void (MqttManager::)(void*)}' to 'TimerCallbackFunction_t {aka void ()(void)}' for argument '5' to 'void* xTimerCreate(const char*, TickType_t, UBaseType_t, void*, TimerCallbackFunction_t)'
Now, from here, having in mind that the problem is around having a pointer to a non-static method that needs somehow to be casted to a free function pointer, three doubts arise:
Why on earth the std::bind "approach" works for WiFi.onEvent but not for xTimerCreate? They seem pretty similar to me... WiFi is typedef void (*WiFiEventCb)(system_event_id_t event); while the timer typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
How can I make this work? Is there a cast or a better approach?
Is this bad practice? My goal here was to enclose mqtt and wifi functions and callbacks in a neat class easily recognizable, organized and maintainable; but I guess that sometimes you just obtain the opposite result without noticing...
FreeRTOS code is plain old C. It knows nothing about C++, instance methods, function objects, etc. It takes a pointer to a function, period. As Armandas pointed out, WiFi.onEvent on the other hand is C++, lovingly written by someone to accept output from std::bind().
There is a workaround. When you read the xTimerCreate API docs, there is a sneaky little parameter pvTimerID which is effectively user-specified data. You can use this to pass a pointer to your class and later retrieve it from inside the callback function using pvTimerGetTimerID(). With a class pointer you can then forward the callback to your C++ class. See example below.
It's good practice to try to hide private class methods and data. Unfortunately this only works well if you're working entirely in C++ :) If calling into C libraries (like FreeRTOS) I find myself breaking such idealistic principles occasionally.
Here's how I'd do it. I use a lambda (without context) as the actual callback function because it's throwaway wrapper code, and the C libraries happily accept it as a plain old function pointer.
auto onTimer = [](TimerHandle_t hTmr) {
MqttManager* mm = static_cast<MqttManager*>(pvTimerGetTimerID(hTmr)); // Retrieve the pointer to class
assert(mm); // Sanity check
mm->connectToMqtt(hTmr); // Forward to the real callback
}
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, static_cast<void*>(this), onTimer);
std::bind returns a callable object, not a function pointer. It works with WiFi.onEvent because there is an overload taking a std::function:
typedef std::function<void(arduino_event_id_t event, arduino_event_info_t info)> WiFiEventFuncCb;
// ...
wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
Solution
Create a static function for the timer callback and simply get the MqttManager instance as you would from anywhere else.

windows c++ multi thread

I am having some trouble with multi threaded c++ code on windows.
class test
{
public:
bool flag;
test() {flag=true;}
void start_do(){while(flag) puts("doing...");}
void stop_do() {flag=0;}
}
int main()
{
test t;
HANDLE h=CreateThread(0,0,(LPTHREAD_START_ROUTINE)t.start_do,0,1,0);
Sleep(5000);
t.stop_do();
return 0;
}
I want to change the doing state with the flag. But it doesn't work.
Could someone give me some help!
The entire code does not make much sense.
first of all, Windows API is a C api. C has no knowing of what a class or method is. C only knows global functions. so passing member function is the first mistake.
secondly, the member function you provided does not look like what CreateThread expects to! you should supply a function with the signature DWORD __stdcall (void*), you function does not look like that at all. casting it by force will only make more troubles.
thirdly, the way to pass a member function is with the sintax &ClassName::functionName. writing object.function means nothing.
finally, C++ has much simpler way of creating threads , and using them as objects, not handles:
test t;
std::thread t([&]{ t.start_do(); });
now, I don't recommend using winapi for creating threads unless you have really good reason why (like specifying the stack size, and if the stack memory is reserved or commited, etc.)
for the sake of the disscution here, the way to make you example to work is by "flattening" the object into void* and re-cast it back inside some global function:
DWORD __stdcall callStartDo(void* pObject){
auto object = reinterpret_cast<test*>(pObject);
if (object){
object->start_do();
}
return 0U;
}
//...
test t;
unsigned long threadID = 0U;
CreateThread(nullptr,0U,&callStartDo,&t,0,&threadID);
and again, this examle shows how to do it only, I strongly advice using std::thread instead. (look at how much overhead is involved vs. the C++ way!)
You can use <thread> though.
cplusplus.com - <thread>
It can be a little hard to understand threads,cause I did.
But it will be easy if you look at the link I added.I think.

why do we need to call these functions at run time using function pointers. we can as well call them directly

Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when we use function pointers, because it seems we just call a function through a pointer to it instead of calling directly?
Thanks
ps: There have been some questions asked here regarding callbacks and function pointers but they do not sufficiently explain my problem.
What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
An practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (eg button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
An source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note: This is from one of my previous answers, here
One very striking reason for why we need function pointers is that they allow us to call a function that the author of the calling code (that's us) does not know! A call-back is a classic example; the author of qsort() doesn't know or care about how you compare elements, she just writes the generic algorithm, and it's up to you to provide the comparison function.
But for another important, widely used scenario, think about dynamic loading of libraries - by this I mean loading at run time. When you write your program, you have no idea which functions exist in some run-time loaded library. You might read a text string from the user input and then open a user-specified library and execute a user-specified function! The only way you could refer to such function is via a pointer.
Here's a simple example; I hope it convinces you that you could not do away with the pointers!
typedef int (*myfp)(); // function pointer type
const char * libname = get_library_name_from_user();
const char * funname = get_function_name_from_user();
void * libhandle = dlopen(libname, RTLD_NOW); // load the library
myfp fun = (myfp) dlsym(libhandle, funname); // get our mystery function...
const int result = myfp(); // ... and call the function
// -- we have no idea which one!
printf("Your function \"%s:%s\" returns %i.\n", libname, funname, result);
It's for decoupling. Look at sqlite3_exec() - it accepts a callback pointer that is invoked for each row retrieved. SQLite doesn't care of what your callback does, it only needs to know how to call it.
Now you don't need to recompile SQLite each time your callback changes. You may have SQLite compiled once and then just recompile your code and either relink statically or just restart and relink dynamically.
It also avoids name collision. If you have 2 libs, both do sorting and both expect you to define a function called sort_criteria that they can call, how would you sort 2 different objects types with the same function?
It would quickly get complicated following all the if's and switches in the sort_criteria function, with callbacks you can specify your own function (with their nice to interpret name) to those sort functions.

multithreading and classes?

Here is the issue that I'm having with multithreading. The proc needs to be static which means the only way I see that 2 threads can communicate and share data is through the global scope. This does not seem very clean nor does it feel very OO. I know I can create a static proc function in a class but that's still static.
What I'd like to for example do is have thread procs in the class somehow so that ex: I could create an MD5 checksum class and have an array of these objects, each on their own thread checking its hash, while the UI thread is not impaired by this and another class could simply keep track of the handles and wait for multiple objects before saying "Complete" or something. How is this limitation usually overcome?
You cannot avoid using a static function if you want to start a thread there. You can however (using Windows) pass the this pointer as a parameter and use it on the other side to enter the class instance.
#include <windows.h>
class Threaded {
static DWORD WINAPI StaticThreadEntry(LPVOID me) {
reinterpret_cast<Threaded*>(me)->ThreadEntry();
return 0;
}
void ThreadEntry() {
// Stuff here.
}
public:
void DoSomething() {
::CreateThread(0, 0, StaticThreadEntry, this, 0, 0);
}
};
In C++, Boost.Thread solves the problem nicely. A thread is represented by a functor, meaning that the (non-static) operator() is the thread's entry point.
For example, a thread can be created like this:
// define the thread functor
struct MyThread {
MyThread(int& i) : i(i) {}
void operator()(){...}
private:
int& i;
};
// create the thread
int j;
boost::thread thr(MyThread(j));
by passing data to the thread functor's constructor, we can pass parameters to the thread without having to rely on globals. (In this case, the thread is given a reference to the integer j declared outside the thread.)
With other libraries or APIs, it's up to you to make the jump from a (typically static) entry point to sharing non-static data.
The thread function typically takes a (sometimes optional) parameter (often of type void*), which you can use to pass instance data to the thread.
If you use this to pass a pointer to some object to the thread, then the thread can simply cast the pointer back to the object type, and access the data, without having to rely on globals.
For example, (in pseudocode), this would have roughly the same effect as the Boost example above:
void MyThreadFunc(void* params) {
int& i = *(int*)params;
...
}
int j;
CreateThread(MyThreadFunc, &j);
Or the parameter can be a pointer to an object whose (non-static) member function you wish to call, allowing you to execute a class member function instead of a nonmember.
I'm not sure I understood well... I give it a try. Are you looking for thread local storage ?
Thread creation routines usually allow you to pass a parameter to the function which will run in a new thread. This is true for both Posix pthread_create(...) and Win32 CreateThread(...). Here is a an example using Pthreads:
void* func (void* arg) {
queue_t* pqueue = (queue_t*)arg;
// pull messages off the queue
val = queue_pull(pqueue);
return 0;
}
int main (int argc, char* argv[]) {
pthread_t thread;
queue_t queue = queue_init();
pthread_create(&thread, 0, func, &queue);
// push messages on the queue for the thread to process
queue_push(&queue, 123);
void* ignored;
pthread_join(&thread, &ignored);
return 0;
}
No statics anywhere. In a C++ program you could pass a pointer to an instance of a class.

Detecting when an object is passed to a new thread in C++?

I have an object for which I'd like to track the number of threads that reference it. In general, when any method on the object is called I can check a thread local boolean value to determine whether the count has been updated for the current thread. But this doesn't help me if the user say, uses boost::bind to bind my object to a boost::function and uses that to start a boost::thread. The new thread will have a reference to my object, and may hold on to it for an indefinite period of time before calling any of its methods, thus leading to a stale count. I could write my own wrapper around boost::thread to handle this, but that doesn't help if the user boost::bind's an object that contains my object (I can't specialize based on the presence of a member type -- at least I don't know of any way to do that) and uses that to start a boost::thread.
Is there any way to do this? The only means I can think of requires too much work from users -- I provide a wrapper around boost::thread that calls a special hook method on the object being passed in provided it exists, and users add the special hook method to any class that contains my object.
Edit: For the sake of this question we can assume I control the means to make new threads. So I can wrap boost::thread for example and expect that users will use my wrapped version, and not have to worry about users simultaneously using pthreads, etc.
Edit2: One can also assume that I have some means of thread local storage available, through __thread or boost::thread_specific_ptr. It's not in the current standard, but hopefully will be soon.
In general, this is hard. The question of "who has a reference to me?" is not generally solvable in C++. It may be worth looking at the bigger picture of the specific problem(s) you are trying to solve, and seeing if there is a better way.
There are a few things I can come up with that can get you partway there, but none of them are quite what you want.
You can establish the concept of "the owning thread" for an object, and REJECT operations from any other thread, a la Qt GUI elements. (Note that trying to do things thread-safely from threads other than the owner won't actually give you thread-safety, since if the owner isn't checked it can collide with other threads.) This at least gives your users fail-fast behavior.
You can encourage reference counting by having the user-visible objects being lightweight references to the implementation object itself [and by documenting this!]. But determined users can work around this.
And you can combine these two-- i.e. you can have the notion of thread ownership for each reference, and then have the object become aware of who owns the references. This could be very powerful, but not really idiot-proof.
You can start restricting what users can and cannot do with the object, but I don't think covering more than the obvious sources of unintentional error is worthwhile. Should you be declaring operator& private, so people can't take pointers to your objects? Should you be preventing people from dynamically allocating your object? It depends on your users to some degree, but keep in mind you can't prevent references to objects, so eventually playing whack-a-mole will drive you insane.
So, back to my original suggestion: re-analyze the big picture if possible.
Short of a pimpl style implementation that does a threadid check before every dereference I don't see how you could do this:
class MyClass;
class MyClassImpl {
friend class MyClass;
threadid_t owning_thread;
public:
void doSomethingThreadSafe();
void doSomethingNoSafetyCheck();
};
class MyClass {
MyClassImpl* impl;
public:
void doSomethine() {
if (__threadid() != impl->owning_thread) {
impl->doSomethingThreadSafe();
} else {
impl->doSomethingNoSafetyCheck();
}
}
};
Note: I know the OP wants to list threads with active pointers, I don't think that's feasible. The above implementation at least lets the object know when there might be contention. When to change the owning_thread depends heavily on what doSomething does.
Usually you cannot do this programmatically.
Unfortuately, the way to go is to design your program in such a way that you can prove (i.e. convince yourself) that certain objects are shared, and others are thread private.
The current C++ standard does not even have the notion of a thread, so there is no standard portable notion of thread local storage, in particular.
If I understood your problem correctly I believe this could be done in Windows using Win32 function GetCurrentThreadId().
Below is a quick and dirty example of how it could be used. Thread synchronisation should rather be done with a lock object.
If you create an object of CMyThreadTracker at the top of every member function of your object to be tracked for threads, the _handle_vector should contain the thread ids that use your object.
#include <process.h>
#include <windows.h>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class CMyThreadTracker
{
vector<DWORD> & _handle_vector;
DWORD _h;
CRITICAL_SECTION &_CriticalSection;
public:
CMyThreadTracker(vector<DWORD> & handle_vector,CRITICAL_SECTION &crit):_handle_vector(handle_vector),_CriticalSection(crit)
{
EnterCriticalSection(&_CriticalSection);
_h = GetCurrentThreadId();
_handle_vector.push_back(_h);
printf("thread id %08x\n",_h);
LeaveCriticalSection(&_CriticalSection);
}
~CMyThreadTracker()
{
EnterCriticalSection(&_CriticalSection);
vector<DWORD>::iterator ee = remove_if(_handle_vector.begin(),_handle_vector.end(),bind2nd(equal_to<DWORD>(), _h));
_handle_vector.erase(ee,_handle_vector.end());
LeaveCriticalSection(&_CriticalSection);
}
};
class CMyObject
{
vector<DWORD> _handle_vector;
public:
void method1(CRITICAL_SECTION & CriticalSection)
{
CMyThreadTracker tt(_handle_vector,CriticalSection);
printf("method 1\n");
EnterCriticalSection(&CriticalSection);
for(int i=0;i<_handle_vector.size();++i)
{
printf(" this object is currently used by thread %08x\n",_handle_vector[i]);
}
LeaveCriticalSection(&CriticalSection);
}
};
CMyObject mo;
CRITICAL_SECTION CriticalSection;
unsigned __stdcall ThreadFunc( void* arg )
{
unsigned int sleep_time = *(unsigned int*)arg;
while ( true)
{
Sleep(sleep_time);
mo.method1(CriticalSection);
}
_endthreadex( 0 );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread;
unsigned int threadID;
if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400) )
return -1;
for(int i=0;i<5;++i)
{
unsigned int sleep_time = 1000 *(i+1);
hThread = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, &sleep_time, 0, &threadID );
printf("creating thread %08x\n",threadID);
}
WaitForSingleObject( hThread, INFINITE );
return 0;
}
EDIT1:
As mentioned in the comment, reference dispensing could be implemented as below. A vector could hold the unique thread ids referring to your object. You may also need to implement a custom assignment operator to deal with the object references being copied by a different thread.
class MyClass
{
public:
static MyClass & Create()
{
static MyClass * p = new MyClass();
return *p;
}
static void Destroy(MyClass * p)
{
delete p;
}
private:
MyClass(){}
~MyClass(){};
};
class MyCreatorClass
{
MyClass & _my_obj;
public:
MyCreatorClass():_my_obj(MyClass::Create())
{
}
MyClass & GetObject()
{
//TODO:
// use GetCurrentThreadId to get thread id
// check if the id is already in the vector
// add this to a vector
return _my_obj;
}
~MyCreatorClass()
{
MyClass::Destroy(&_my_obj);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
MyCreatorClass mcc;
MyClass &o1 = mcc.GetObject();
MyClass &o2 = mcc.GetObject();
return 0;
}
The solution I'm familiar with is to state "if you don't use the correct API to interact with this object, then all bets are off."
You may be able to turn your requirements around and make it possible for any threads that reference the object subscribe to signals from the object. This won't help with race conditions, but allows threads to know when the object has unloaded itself (for instance).
To solve the problem "I have an object and want to know how many threads access it" and you also can enumerate your threads, you can solve this problem with thread local storage.
Allocate a TLS index for your object. Make a private method called "registerThread" which simply sets the thread TLS to point to your object.
The key extension to the poster's original idea is that during every method call, call this registerThread(). Then you don't need to detect when or who created the thread, it's just set (often redundantly) during every actual access.
To see which threads have accessed the object, just examine their TLS values.
Upside: simple and pretty efficient.
Downside: solves the posted question but doesn't extend smoothly to multiple objects or dynamic threads that aren't enumerable.