Alternative to postThreadMessage/peekmessage? - c++

There's a (static) thread in my C++ application, frequently doing something. To exchange information between the thread and my application I use methods PostThreadMessage and PeekMessage.
Due to some reason I can't use these methods anymore but don't know a good alternative. Does anybody have an advice? I just want to exchange simple parameters.

There's no reason why you can't "exchange simple object with the main thread" as you said in a comment. A common pattern for sharing an instance of a class between threads is to do something like this:-
Declare your class with a static function that can be targeted by _beginthread and an instance function that does the work:
class CMyClass
{
// ... other class declarations ...
private:
static void __cdecl _ThreadInit(void *pParam); // thread initial function
void ThreadFunction(); // thread instance function
void StartThread(); // function to spawn a thread
// ... other class declarations ...
};
Define the functions something like this:
void CMyClass::StartThread()
{
// function to spawn a thread (pass a pointer to this instance)
_beginthread(CMyClass::_ThreadInit, 0, this);
}
void __cdecl CMyClass:_ThreadInit(void *pParam)
{
// thread initial function - delegate to instance
CMyClass *pInstance = (CMyClass*)pParam;
pInstance->ThreadFunction();
}
void CMyClass:ThreadFunction()
{
// thread instance function is running on another
// thread but has (hopefully synchronised) access
// to all of the member variables of the CMyClass
// that spawned it ....
}
Makes sense? The general idea is just to use the static function with a passed this pointer to connect back to a specific instance of the class.

Related

sa_handler function; can't access class member

I am trying to build a multi threaded program that will create four instances of a Child and "run" a set of "expensive" Jobs. The parent will send a signal indicating when they shall all start. Now, each child thread must then catch that signal. It has inside of it a sig_handler. It's a private class inside of Child.
So far I have it defined as:
private:
class sig_handler {
typedef struct sigaction sigAct;
Shared* sh;
//============
void whatSig();
public:
sig_handler( Shared* s );
sigAct action;
sigset_t signalset; // Just want siguser and sigquit
static void catchSig( int sig ); // interacts with the shared resource
// it starts up the threads
};
First off, is it even ok to have a class as a signal handler? If it is ok (which would certainly make the readibility better), how would we implement it?
I am trying to catch SIGUSR1 so that I can change a flag in Shared memory. Each thread has access to Shared memory through a pointer to this object, i.e. Shared* share. This is done using a class to act as a kind of shared base.
Now here is what I really need answered. I begin setting up my sigset_t signalSet:
Child::sig_handler::sig_handler( Shared* s ) {
sh = s;
sigemptyset(&signalset);
sigaddset(&signalset, SIGUSR1); // Add these to the now empty set
sigaddset(&signalset, SIGQUIT);
action.sa_handler = catchSig; // 1
action.sa_mask = signalset;
action.sa_flags = 0;
sigaction(SIGUSR1, &action, NULL); // attach the class member action
}
Really pay attention to line 1. This is a critical spot. This I think has to be a static or global function. This is where an error can be happening. When I make my class method catchSig(int sig) non static, line 1 complains Reference to a non-static function call must be called. I have it defined as such when this happens: void catchSig( int sig );
When I define it as static void catchSig( int sig );, the compiler complains on line 2.
void Child::sig_handler::catchSig(int sig) {
sh->startflag; // 2
}
It says, Invalid use of 'sh' in static member function. I need to be able to have access to this variable. How can I fix it so that I can have my sig_handler class, and share through catchSig()?
Update:
I implemented StoryTeller's suggestion of using a pointer to this. While it worked to stop the complaining of the compiler, I still have a buildtime error. I altered the definition of sig_handler to now be this:
private:
class sig_handler {
typedef struct sigaction sigAct;
Shared* sh;
static sig_handler* self;
//============
void whatSig();
public:
sig_handler( Shared* s );
sigAct action;
sigset_t signalset;
static void catchSig( int sig ); // interacts with the shared resource
// it starts up the threads
};
Take note of the new static pointer to itself. This was done so that I can have access to the variable sh, the shared resource that I need. Which I use as such:
void Child::sig_handler::catchSig(int sig) {
self->sh->setStartFlag(true); // this was were it used to complain
}
The sig_handler is created in the Child constructor (sigHand = new sig_handler(share)). I get a build time error stated below. What is happening? How can this be fixed?
"Child::sig_handler::self", referenced from:
Child::sig_handler::sig_handler(Shared*) in Child.o
Child::sig_handler::catchSig(int) in Child.o
ld: symbol(s) not found for architecture x86_64
Update 2:
Essentially, it's not possible to make a sig_handler class unfortunately.

Starting a thread from a member function while inside another class's member function

I need to start a thread that calls a public member function of the class Foo while inside of a public function that belongs to the class Bar. How do I achieve this?
I have tried the following (made trivial):
void Bar::BarFunc()
{
// Do some BarFunc stuff
// Start a thread that needs to do stuff independently of BarFunc
std::thread t(&Foo::FooFunc, FooFunc params,..,.., ???);
t.detach();
return;
}
This is my first time dealing with threading and the actual problem is a little more complex - BarFunc is a virtual function of a State class, with n-concrete classes implementing the different states my application can exist in, hence the question. I am not sure what to put as the last parameter, if anything. I have looked at this answer but cannot discern which syntax to use, if any of them even apply.
Finally, if this is bad practice all together, I would be grateful for any design advice.
You likely have to manage two instances:
An instance of Foo
A thread executing a member function of Foo
That leads to the following sketch of a class Bar:
#include <iostream>
#include <thread>
struct Foo{
void print(std::string s) { // by value!
std::cout << s;
}
};
class Bar{
public:
void hello() {
// Ensure the thread is not running
// (Only one thread is supported in this example)
if( ! foo_thread.joinable()) {
// Move a newly constructed thread to the class member.
foo_thread = std::thread(
&Foo::print, // pointer to member function of Foo
&foo, // pointer to the instance of Foo
"hello\n" // arguments by value
);
}
}
~Bar() {
// Ensure the thread has been started.
if(foo_thread.joinable()) {
// This will block until the thread has finished.
foo_thread.join();
}
}
private:
Foo foo;
std::thread foo_thread;
};
int main()
{
Bar bar;
bar.hello();
}
Note: The thread is not detached. A detached (not maintained properly) running thread, will get killed at end of the program and resources used by that thread (e.g.: file handles) might not be returned to the system.

How to start a boost::thread running a member function?

I have a real time controller application with a number of hardware devices of different types connected.
All devices share a lot of code, but each has also some device type specific stuff. I'm trying to write this code to be easy to extend with new types of hw.
Each connected device should have an event manager function running in a separate thread.
I would like to keep the common stuff in a base class, lets call it "Device" and just put the hardware specific code in the derived classes.
So I create a Device base class with the common stuff and make the event manager a pure virtual, and then each derived class implements it.
Then at system start I create a vector of all the connected hardware devices, and push pointers to instances of the appropriate derived class into it.
Now I would like to start a boost::thread for each instance in the vector, and each thread should execute the event manager function from that instance in the vector.
So I try something like:
Class Device {
...
boost::thread thread;
void manager() = 0;
...
}
Class SpecificDevice1 : public Device {
...
void manager();
}
SpecificDevice1::manager() {
...do stuff here...
}
Class SpecificDevice2 : public Device {
...
void manager();
}
SpecificDevice2::manager() {
...do stuff here...
}
Class Config {
...
std::vector<Device*> devices;
...
}
Config config;
...config.devices get populated with pointers to instances of SpecificDevice1 and SpecificDevice2...
for( auto &device : config.devices ) {
device->thread = boost::thread( device->manager );
};
I have tried many different permutation of this but I always end up with
error: no matching function for call to 'boost::thread::thread()'
...even if I dynamic_cast device to a pointer to the appropriate SpecificDeviceX class, I still get the same error.
The boost::thread constructor needs a function pointer, and an instance to the actual object (for the this pointer in the member function).
For this use can use the Thread Constructor with arguments:
device->thread = boost::thread(&Device::manager, device);
The first argument is a pointer to the member function, and the second is a pointer to an instance of Device.
There is another change you must do for this to work though, and that is to make the manager function virtual, for the proper function would be called:
Class Device {
...
boost::thread thread;
virtual void manager() = 0;
...
}
By the way, since you are using a compiler supporting C++11, I suggest you change to std::thread if possible.

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.

How to pass parameters to a Thread object?

I'm working with a C++ class-library that provides a Thread base-class where the user has to
implement a run() method.
Is there a recommended way on how to pass parameters to that run() method? Right now
I prefer to pass them via the constructor (as pointers).
I'm not sure about C++, but that's how you would do it in Java. You'd have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Must be the same in your case.
An alternative is to extend this Thread class to accept a functor as only constructor parameter, so that you can bind any call inside it.
Then the class using threads wont need to inherit from Thread, but only have one (or more) Thread member. The functor calls any start point you want ( some method of the class with any parameters )
Here is a typical pattern:
1) Define a data structure that encapsulates all the data your thread needs
2) In the main thread, instantiate a copy of the data structure on the heap using operator new.
3) Fill in the data structure, cast the pointer to void*, pass the void* to the thread procedure by whatever means you are provided by your thread library.
4) When the worker thread gets the void*, it reinterpret_cast's it to the data structure, and then takes ownership of the object. Meaning when the thread is done with the data, the thread deallocates it, as opposed to the main thread deallocating it.
Here is example code you can compile & test in Windows.
#include "stdafx.h"
#include <windows.h>
#include <process.h>
struct ThreadData
{
HANDLE isRunning_;
};
DWORD WINAPI threadProc(void* v)
{
ThreadData* data = reinterpret_cast<ThreadData*>(v);
if( !data )
return 0;
// tell the main thread that we are up & running
SetEvent(data->isRunning_);
// do your work here...
return 1;
}
int main()
{
// must use heap-based allocation here so that we can transfer ownership
// of this ThreadData object to the worker thread. In other words,
// the threadProc() function will own & deallocate this resource when it's
// done with it.
ThreadData * data = new ThreadData;
data->isRunning_ = CreateEvent(0, 1, 0, 0);
// kick off the new thread, passing the thread data
DWORD id = 0;
HANDLE thread = CreateThread(0, 0, threadProc, reinterpret_cast<void*>(data), 0, &id);
// wait for the worker thread to get up & running
//
// in real code, you need to check the return value from WFSO and handle it acordingly.
// Here I assume the retval is WAIT_OBJECT_0, indicating that the data->isRunning_ event
// has become signaled
WaitForSingleObject(data->isRunning_,INFINITE);
// we're done, wait for the thread to die
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
return 0;
}
A common problem with thread startup is that the arguments passed exist on only the stack in the calling function. Thread startup is often deferred, such that the calling function returns and it is only some time later the thread actually starts - by which time the arguments are no longer in existence.
One solution to this is to create an event and then start the thread, passing the event as one of the arguments. The starting function then waits on the event, which is signalled by the thread when it has completed startup.
You can pass the parameters as members of the thread class. The thread which creates the thread can presumably call other methods and/or call member functions before the thread starts. Therefore it can populate whatever members are necessary for it to work. Then when the run method is called, it will have the necessary info to start up.
I am assuming that you will use a separate object for each thread.
You would normally put all the threads you create into an array, vector etc.
It is ok to pass them via constructor. Just be sure that pointers will live longer than the thread.
Well, I'd prefer to put the parameters in the Start() method, so you can have a protected constructor, and doesn't have to cascade the parameters through derived class constructor.
I'd prolly let my decleration look something like this:
class Thread
{
public:
virtual void Start(int parameterCount, void *pars);
protected:
Thread();
virtual void run(int parameterCount, void *pars) = 0;
}
Just make sure that your parameters are somehow contracted, e.g. #1 will be int, #2 will be a double etc. etc. :)