mem_fun fails, pthread and class ptr - c++

pthread takes in as its parameter void *(*start_routine)(void* userPtr), I was hoping I can use std::mem_fun to solve my problem but I cant.
I would like to use the function void * threadFunc() and have the userPtr act as the class (userPtr->threadFunc()). Is there a function similar to std::mem_func that I can use?

One way is to use a global function that calls your main thread function:
class MyThreadClass {
public:
void main(); // Your real thread function
};
void thread_starter(void *arg) {
reinterpret_cast<MyThreadClass*>(arg)->main();
}
Then, when you want to start the thread:
MyThreadClass *th = new MyThreadClass();
pthread_create(..., ..., &thread_starter, (void*)th);
On the other hand, if you don't really need to use pthreads manually, it might be a good idea to have a look at Boost.Thread, a good C++ thread library. There you get classes for threads, locks, mutexes and so on and can do multi-threading in a much more object-oriented way.

Related

Initialize C++ Thread and Run Later

I'm assuming there's an easy answer to this question. I want to first define a thread as a member variable of a class, and then later start this thread in a different function.
For example:
The header file:
#include<thread>
class Foo{
public:
void threaded_method();
void start_thread();
private:
std::thread m_thread;
};
Cpp file:
void Foo::start_thread(){
m_thread = std::thread(threaded_method);
}
Although the above does not work, thoughts?
To pass a member function to a thread, you must also pass an instance on which to execute that function.
void Foo::start_thread(){
m_thread = std::thread(&Foo::threaded_method, this);
}
Found a good example in these pages:
http://en.cppreference.com/w/cpp/thread/thread/joinable
Start thread with member function
I forgot to pass in a valid reference to the member function.
void Foo::start_thread(){
m_thread = std::thread(&Foo::threaded_method, this);
}
Should work. Love finding the answer right after I post a question...
You might also simply change your architecture. For example, have a list and which would contain the functions you want to perform. Then multithread your way through all the functions you want to run.

C++/MFC/ATL Thread-Safe String read/write

I have a MFC class with threads launched and the threads need to modify CString members of the main class.
I hate mutex locks, so there must be a an easier way to do this.
I am thinking to use the boost.org library or atl::atomic or shared_ptr variables.
What is the best method of reading and writting the string and be thread safe?
class MyClass
{
public:
void MyClass();
static UINT MyThread(LPVOID pArg);
CString m_strInfo;
};
void MyClass::MyClass()
{
AfxBeginThread(MyThread, this);
CString strTmp=m_strInfo; // this may cause crash
}
UINT MyClass::MyThread(LPVOID pArg)
{
MyClass pClass=(MyClass*)pArd;
pClass->m_strInfo=_T("New Value"); // non thread-safe change
}
According to MSDN shared_ptr works automatically https://msdn.microsoft.com/en-us/library/bb982026.aspx
So is this a better method?
#include <memory>
class MyClass
{
public:
void MyClass();
static UINT MyThread(LPVOID pArg);
std::shared_ptr<CString> m_strInfo; // ********
};
void MyClass::MyClass()
{
AfxBeginThread(MyThread, this);
CString strTmp=m_strInfo; // this may cause crash
}
UINT MyClass::MyThread(LPVOID pArg)
{
MyClass pClass=(MyClass*)pArd;
shared_ptr<CString> newValue(new CString());
newValue->SetString(_T("New Value"));
pClass->m_strInfo=newValue; // thread-safe change?
}
You could implement some kind of lockless way to achieve that, but it depends on how you use MyClass and your thread. If your thread is processing some data and after processing it, it need to update MyClass, then consider putting your string data in some other class ex.:
struct StringData {
CString m_strInfo;
};
then inside your MyClass:
class MyClass
{
public:
void MyClass();
static UINT MyThread(LPVOID pArg);
StringData* m_pstrData;
StringData* m_pstrDataForThreads;
};
now, the idea is that in your ie. main thread code you use m_pstrData, but you need to use atomics to store local pointer to it ie.:
void MyClass::MyClass()
{
AfxBeginThread(MyThread, this);
StringData* m_pstrDataTemp = ATOMIC_READ(m_pstrData);
if ( m_pstrDataTemp )
CString strTmp=m_pstrDataTemp->m_strInfo; // this may NOT cause crash
}
once your thread finished processing data, and wants to update string, you will atomically assign m_pstrDataForThreads to m_pstrData, and allocate new m_pstrDataForThreads,
The problem is with how to safely delete m_pstrData, I suppose you could use here std::shared_ptr.
In the end it looks kind of complicated and IMO not really worth the effort, at least it is hard to tell if this is really thread safe, and when code will get more complicated - it will still be thread safe. Also this is for single worker thread case, and You say you have multiple threads. Thats why critical section is a starting point, and if it is too slow then think of using lockless approach.
btw. depending on how often you string data is updated you could also think about using PostMessage to safely pass a pointer to new string, to your main thread.
[edit]
ATOMIC_MACRO does not exists, its just a place holder to make it compile use ie. c++11 atomics, example below:
#include <atomic>
...
std::atomic<uint64_t> sharedValue(0);
sharedValue.store(123, std::memory_order_relaxed); // atomically store
uint64_t ret = sharedValue.load(std::memory_order_relaxed); // atomically read
std::cout << ret;
I would have used simpler approach by protecting the variable with a SetStrInfo:
void SetStrInfo(const CString& str)
{
[Lock-here]
m_strInfo = str;
[Unlock-here]
}
For locking and unlocking we may use CCriticalSection (member of class), or wrap it around CSingleLock RAII. We may also use slim-reader writer locks for performance reasons (wrap with RAII - write a simple class). We may also use newer C++ techniques for RAII locking/unlocking.
Call me old-school, but for me std namespace has complicated set of options - doesn't suit everything, and everyone.

[C++]Would this be a valid approach for a 'sleep' function in a thread?

I would like to implement a sleep() function in my thread class, but I don't know if this is a valid/proper way to do it.
This is my entire thread class (thread.h):
#include <process.h>
struct RUNNABLE{
virtual void run() = 0;
};
class thread{
public:
void start(void *ptr){
DWORD thr_id;
HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id);
}
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
private:
static unsigned int __stdcall thread_proc(void *param){
((RUNNABLE*)param)->run();
_endthreadex(0);
return 0;
}
};
And as you're probably able to sort out, this is my sleep() function:
void sleep(int sleep_time, bool alertable){
SleepEx(sleep_time, alertable);
}
But will this make the actual thread contained inside this thread instance sleep for the specified amount of milliseconds?
Best regards,
Benjamin :).
EDIT:
So according to atzz, I could define the sleep function as a static member function, and have that call ::SleepEx(), and that would allow me to call it like this:
class test : RUNNABLE{
virtual void run(){
printf("hi");
thread::sleep(1000, false);
}
};
and then that'll cause the thread executing the 'test' runnable to sleep 1000 milliseonds?
It will put to sleep whichever thread calls this member function.
No, this will put the original thread to sleep, not the one you start.
Yes it will -- provided that it's called from that thread (i.e. from within thread::run()).
Due to this, I'd recommend making sleep() a protected member function.
Or, as an alternative, make it a static method, with semantics of thread::sleep() being a service that pauses calling thread (this approach is used, e.g., in Java standard library).
It is not possible to make an other than calling thread sleep, because the thread can be in the middle of something at that moment.
If you need to suspend newly created thread, you should use SuspendThread instead or pass CREATE_SUSPENDED to _beginthreadex(), but this can cause deadlocks in some cases
see http://msdn.microsoft.com/en-us/library/ms686345%28v=VS.85%29.aspx

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 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?