windows c++ multi thread - c++

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.

Related

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

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.

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.

Call function after certain time has elapsed

I'm making a GUI API (for games, not an OS) and would like to implement animated buttons. I'd like to be able to create timed events, but, within the class.
example:
class TextBox
{
void changeColor(int color);
void createTimedEvent(func* or something, int ticks);
void animate()
{
createTimedEvent(changeColor(red),30);
}
};
So in this example, the timer would call the class instance's changeColor function, with argument red, after 30 ms. Is there a way to do this?
Basically, a function to call a function, which could be a function from a instancable class, wit n arguments, after a given interval has expired.
The precision of the timer is not a big deal for me.
Thanks
I believe you could make this work portably using Boost.Asio - this is primarily designed for async I/O but I see no reason why the timer code cannot be used in other contexts. See this example for how to kick off a timer which calls back your code after expiry.
The only proviso I noticed is that you have to call ioservice::run in some thread with the ioservice instance you used here, or the callbacks will not happen.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(print);
// ensure we call io.run() from some thread or callbacks will not happen
// other app logic
return(0);
}
There is also a discussion of this very topic on MSDN blogs here by the author of the library.
I'd welcome anybody showing otherwise, but as far as I know, you'd need to deal with this in steps. The first step is to create a bound function -- i.e., take the function you specify, and create an object that, when you invoke it, in turn invokes the specified function with the specified parameters. Using Boost/TR1/C++0x bind, that much would look something like this:
std::tr1::function<void (int)> func(std::tr1::bind(&TextBox::changColor, this, red));
That makes func an object that will invoke TextBox::changeColor(red) when it's called. There is one minor problem with this though: func is an object, not really a function. Syntactically, using it looks like calling a function, but that's an illusion created by the C++ compiler; trying to pass that object's address to something that will use it as the address of a function will fail (probably pretty spectacularly). Unfortunately, at least in Windows, there's no way to designate an arbitrary parameter that will be passed to a timer callback function (though you could probably manage to do it in the nIdEvent parameter with some really gross casting, something like:
void callback(HWND, UINT, UINT_PTR f, DWORD) {
typedef std::tr1::function<void (int)> function;
function *func = reinterpret_cast<function *>(f);
(*func)();
}
To make this a bit cleaner, instead of casting the address to an unsigned integer, I'd consider saving the address of the callback in an array, and passing its index in the array instead:
void callback(HWND, UINT, UINT_PTR f, DWORD) {
callback_functions[f]();
}
That leaves the really non-portable part: actually getting the system to invoke that function after the right length of time. Though most modern systems have one, each is still unique. Under Windows (for one example) you could do something like this:
callback_functions[++N] = func;
SetTimer(hWnd, N, 30, callback);
For such a simple idea, that's all too ugly and complex an answer, but I honestly don't know of anything much less complex that'll work. If you have almost any reasonable choice in the matter, I'd use something else. Also note that this is really a stream-of-consciousness sketch -- none of the code has been compiled, much less really tested. I can't see a good reason the general idea shouldn't work, but it might take a fair amount of effort to flesh it out to something that really does (e.g., I've mostly neglected management of the "callback_functions" array).

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.

How to maintain a list of functions in C++/STL?

Before asking you my question directly, I'm going to describe the nature of my prolem.
I'm coding a 2D simulation using C++/OpenGL with the GLFW library. And I need to manage a lot of threads properly. In GLFW we have to call the function:
thread = glfwCreateThread(ThreadFunc, NULL); (the first parameter is the function that'll execute the thread, and the second represents the parameters of this function).
And glfwCreateThread, has to be called every time! (ie: in each cycle). This way of working, doesn't really help me, because it breaks the way i'm building my code because i need to create threads out of the main loop scope. So I'm creating a ThreadManager class, that'll have the following prototype :
class ThreadManager {
public:
ThreadManager();
void AddThread(void*, void GLFWCALL (*pt2Func)(void*));
void DeleteThread(void GLFWCALL (*pt2Func)(void*));
void ExecuteAllThreads();
private:
vector<void GLFWCALL (*pt2Func)(void*)> list_functions;
// some attributs
};
So for example, if I want to add a specific thread I'll just need to call AddThread with the specific parameters, and the specific function. And the goal is just to be able to call: ExecuteAllThreads(); inside the main loop scope. But for this i need to have something like:
void ExecuteAllThreads() {
vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter_end = list_functions.end();
for(vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(&(iter*), param);
}
}
And inside AddThread, I'll just have to add the function referenced by the pt2Func to the vector : list_functions.
Alright, this is the general idea of what i want to do.. is it the right way to go ? You have a better idea ? How to do this, really ? (I mean the problem is the syntax, i'm not sure how to do this).
Thank you !
You need to create threads in each simulation cycle? That sounds suspicious. Create your threads once, and reuse them.
Thread creation isn't a cheap operation. You definitely don't want to do that in every iteration step.
If possible, I'd recommend you use Boost.Thread for threads instead, to give you type safety and other handy features. Threading is complicated enough without throwing away type safety and working against a primitive C API.
That said, what you're asking is possible, although it gets messy. First, you need to store the arguments for the functions as well, so your class looks something like this:
class ThreadManager {
public:
typedef void GLFWCALL (*pt2Func)(void*); // Just a convenience typedef
typedef std::vector<std::pair<pt2Func, void*> > func_vector;
ThreadManager();
void AddThread(void*, pt2Func);
void DeleteThread(pt2Func);
void ExecuteAllThreads();
private:
func_vector list_functions;
};
And then ExecuteAllThreads:
void ExecuteAllThreads() {
func_vector::const_iterator iter_end = list_functions.end();
for(func_vector::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(iter->first, iter->second);
}
}
And of course inside AddThread you'd have to add a pair of function pointer and argument to the vector.
Note that Boost.Thread would solve most of this a lot cleaner, since it expects a thread to be a functor (which can hold state, and therefore doesn't need explicit arguments).
Your thread function could be defined something like this:
class MyThread {
MyThread(/* Pass whatever arguments you want in the constructor, and store them in the object as members */);
void operator()() {
// The actual thread function
}
};
And since the operator() doesn't take any parameters, it becomes a lot simpler to start the thread.
What about trying to store them using boost::function ?
They could simulate your specific functions, since they behave like real objects but in fact are simple functors.
Consider Boost Thread and Thread Group
I am not familiar with the threading system you use. So bear with me.
Shouldn't you maintain a list of thread identifiers?
class ThreadManager {
private:
vector<thread_id_t> mThreads;
// ...
};
and then in ExecuteAllThreads you'd do:
for_each(mThreads.begin(), mThreads.end(), bind(some_fun, _1));
(using Boost Lambda bind and placeholder arguments) where some_fun is the function you call for all threads.
Or is it that you want to call a set of functions for a given thread?