Thread safety for multiple instance of object and multithreading - c++

I want to each of these 3 object instance run in parallel. I have no global variables. Is it thread-safe? or do i need some syncronization mechanism?
class myClass{
public:
myClass();
~myClass();
void myFunction();
}
int main() {
myClass myObj1, myObj2, myObj3;
pthread_t myThread1, myThread2, myThread3;
pthread_create(&myThread1, NULL, myObj1::myFunction, NULL );
pthread_create(&myThread2, NULL, myObj2::myFunction, NULL );
pthread_create(&myThread3, NULL, myObj3::myFunction, NULL );
...
}
Could you explain me why or why not need for syncronization?
EDIT: In the below, some friends say that this program cannot compile because while creating pthread i used non-static member function call. I just wanted to show what is my problem here. For Friends who want to use non-static member function with pthreads, its my code;
struct thread_args{
myClass* itsInctance;
//int i,j,k; // also if you want to pass parameter to function you use in
//pthread_create u can add them here
}
void* myThread(void* args){
thread_args *itsArgs = (thread_args*)args;
itsArgs->itsInstance->myFunciton();
}
int main() {
myClass myObj1;
pthread_t myThread1;
thread_args itsArgs;
itsArgs.itsInstance = &myObj1;
// also if you have any other params, fill them here
pthread_create(&myThread1, NULL, myThread, &itsArgs);
...
}

Could you explain me why or why not need for syncronization?
You need synchronization when there is a data race.
Since in your example there is no data, there cannot be a data race.
You may find video Plain Threads are the GOTO of todays computing - Hartmut Kaiser - Keynote Meeting C++ 2014 instructive.

Related

Posix Thread Class and Start Routines (pthread)

I would like to implement a thread class using pthread.
Of course I would like to have different starting routines for each thread I'm creating.
pthread_create tho allows only a static function as starting routine, so it can't be instantiated.
Is there a way to allow that or is it better to use a struct to handle my threads ?
This is the code I wrote sofar:
class thread {
string name;
pthread_t id;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_attr_t attr;
public:
thread (string t_name);
static void* start(void*);
int id_get();
private:
};
thread::thread (string t_name)
{
name = t_name;
pthread_attr_init(&attr);
int stacksize = sizeof(double) * TH_STACK_SIZE * 30;
pthread_attr_setstacksize(&attr, stacksize);
int rc = pthread_create (&id, &attr, &start, NULL);
cout << "return_code: " << rc << endl;
cout << id;
}
void* thread::start(void*)
{
while(1){
cout << "here";
pthread_exit(NULL);
}
}
int thread::id_get()
{
return id;
}
and my test main:
int main(void) {
cout << "Creating threads" << endl;
thread test1("first");
thread test2("second");
pthread_join(test1.id_get(),NULL);
pthread_join(test2.id_get(),NULL);
return 0;
}
I would like to have different starting routines for each thread I'm
creating.
Back when I used posix thread, (I now use std::thread), I used a 'two-step' entry mechanism. At the (small) cost of these two steps, every class could easily have its own thread.
I always keep these entry methods private.
class Foo_t
{
// ... etc
private:
static void* threadEntry(void* ptr);
void* threadEntry2(void); // thread actions in an object method
// ... etc
}
Because these are private, the class has some public method to create the posix thread, typically something like:
void Foo_t::startApp()
{
// ... etc
int pcStat = m_Thread.create(Foo_t::threadEntry, this);
// this 2 parameter method of my thread wrapper class
// invoked the 4 parameter "::pthread_create(...)".
// The 'this' param is passed into the 4th parameter, called arg.
dtbAssert(0 == pcStat)(m_nodeId)(pcStat)(errno);
// ...
}
Note the second parameter, 'this', to m_Thread.create().
The thread would start in the static method:
void* Foo_t::threadEntry(void* a_ptr)
{
dtbAssert(a_ptr != 0);
Foo_t* a_foo = static_cast<Foo_t*>(a_ptr);
void* retVal = a_foo->threadEntry2();
return(retVal);
}
Here, the void* parameter is filled in with the 'this' pointer of the class instance, and then static_cast back to what we need, a Foo_t*. Remember, this method is private, so only startApp() would create a thread.
Note that threadEntry() invokes an actual method of the class instance called:
void* Foo_t::threadEntry2(void)
{
DBG("Thread %2d (id=%lx): sems %p/%p, "
"Entering sem controlled critical region\n", ...);
// ... start thread work
}
And from here, any method of the instance is available.
So, what next. There are so many ways to proceed to different thread routines.
Consider adding a parameter to startApp:
void Foo_t::startApp(int select);
The 'int select' and a switch/case statement could run a unique threadEntry().
Perhaps the 'int select' could be installed (in the instance) so that a later switch/case in threadEntry() could run a unique method or threadEntry2_x().
Or perhaps the switch/case might be installed in threadEntry2().
Consider that the startApp parameter might be a method pointer.
void Foo_t::startApp(<method pointer>);
The method pointer could be (somewhat more directly) invoked instead of the 'fixed' name threadEntry2().
The above are small issues.
Mutex and having more than 1 thread running in an instance are bigger issues.
I have indeed had multiple threads 'running-around' in a single class instance. For that I used critical sections, under mutex or some other guard mechanisms. std::mutex is convenient, and works with 'Posix' threads, but, on Ubuntu, I often use a Posix Process Semaphore, set to Local mode (unnamed, unshared). PPLSem_t is efficient and fits into 4 one line methods wrapped in a small class.
pthread_create tho allows only a static function as starting routine,
so it can't be instantiated.
There is no difficulty instantiating an instance of a class containing a static method. I'm not sure what you mean in this statement / context.
Review the approach I have detailed above, and you should quickly get to functioning Posix threads in your class instance.
Remember to check on stack usage and how much ram is available on your ARM system. The Ubuntu default stack size is 8 MBytes. Perhaps your ARM provides stack size control.
If you have POSIX threads availble, std::thread will be available for any C++ compiler supporting the current standard (since c++11).
So basically you don't need to roll your own thread class for your cross compiled target (e.g. GCC supports that since version 4.9 or so).
But in general your approach is correct. To make it applicable for various classes you can simmply make the thread class a template:
template<typename T>
class thread {
string name;
pthread_t id;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_attr_t attr;
public:
thread (string t_name, T& runnable);
static void* start(void*);
int id_get();
T& runnable_;
};
And implement the constructor and start() function as follows:
template<typename T>
thread<T>::thread (string t_name)
: name(t_name)
, runnable_(runnable)
{
pthread_attr_init(&attr);
int stacksize = sizeof(double) * TH_STACK_SIZE * 30;
pthread_attr_setstacksize(&attr, stacksize);
int rc = pthread_create (&id, &attr, &start, this);
// ^^^^
cout << "return_code: " << rc << endl;
cout << id;
}
template<typename T>
void* thread<T>::start(void* pThis) {
thread<T>* realThis = reinterpret_cast<thread<T>*>(pThis);
(realThis->runnable)_.start();
pthread_exit(NULL);
}
The thread class can be used then like follows:
struct MyRunnable {
MyRunnable(/* Whatever parameters needed */)
: /* Whatever needs to be initialized */ {
}
void start() {
/* Full access to all class member variables */
}
}
int main() {
MyRunnable run(/* Whatever parameters needed */);
thread<MyRunnable> t("TheTreadName",run); // start() will execute here
// do concurrent stuff
t.join();
}
I just would choose a different name as thread to avoid any clashes with the c++ standard library.

Pointer to this* in thread

I have a class and a library (lwip). For some reasons I need to call library's function of thread creation like :
/** The only thread function:
* Creates a new thread
* #param name human-readable name for the thread (used for debugging purposes)
* #param thread thread-function
* #param arg parameter passed to 'thread'
* #param stacksize stack size in bytes for the new thread (may be ignored by ports)
* #param prio priority of the new thread (may be ignored by ports) */
sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int
stacksize, int prio);
Inside this function we call pthread:
code = pthread_create(&tmp,NULL,(void *(*)(void *)) function, arg);
My call looks like :
sys_thread_new("main_thread",(lwip_thread_fn)&this->main_thread, NULL,
DEFAULT_THREAD_STACKSIZE,DEFAULT_THREAD_PRIO);
My class method works fine, but I need to change some fielsd of CURRENT class (like 'state'
or else) I have an Idea to pass a pointer to current class to that thread and in thread function change class fields. Some kind of:
sys_thread_new("main_thread",(lwip_thread_fn)&this->main_thread, (void*)this,
DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO);
Then in main_thread:
void lwip::main_thread(void *arg) {
lwip *p = (lwip*)arg;
p->state = 1;
}
Something like that. But it seems I do something wrong -
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff6e8e700 (LWP 4985)]
0x0000000000403a75 in lwip::main_thread (this=0x7fffffffe4f0, arg=0x80) at
../src/lwip.cpp:50
50 p->state = 1;
There are two problems here: If the main_thread member function is a static member function, you pass a pointer to it using &lwip::main_thread, no casting should be needed. If the function is not static, then you must make it static.
The other problem is that if the instance (this) you pass to the thread function is destructed, the thread function now has a pointer to a destructed object. Be careful with temporary object or passing instances by value.
If the actual thread function can't be static, you can easily solve it with a static wrapper function:
class lwip
{
...
private:
void main_thread() { ... }
static void* main_thread_wrapper(void* arg)
{
reinterpret_cast<lwip*>(arg)->main_thread();
return nullptr;
}
};
...
sys_thread_new("main_thread", &lwip::main_thread_wrapper, this,
DEFAULT_THREAD_STACKSIZE,DEFAULT_THREAD_PRIO);
If you have to cast the pointer to function to get
pthread_create to compile, you have undefined behavior.
If the goal is to call a member function in a different thread,
you need to wrap the call in an extern "C" function. This
means no members and no templates; in the simplest case:
extern "C" void*
startThread( void* p )
{
static_cast<T*>(p)->f();
}
and pass the address of startThread as third argument and
a pointer to the object as fourth. If inheritance is involved,
you must ensure that the fourth argument has the same type as
that in the cast in startThread, e.g.:
pthread_create( &tmp, nullptr, &startThread, static_cast<Base*>( pointerToDerived ) );
if startThread casts to Base*.
If you need arguments to the function as well, you need to pass
a pointer to a struct with both the pointer to the object and
the additional arguments. You also need to ensure that the
lifetime of this struct is sufficient, so that there is no risk
of the thread accessing an already inexistant object. This
often means an additional conditional variable, to ensure that
the thread calling pthread_create doesn't continue before the
new thread has made a copy of all of the relevant data. (Both
Boost threads and the C++11 threads do this for you. It's only
necessary if you need additional data, other than just the
pointer to the object, in the new thread.)
This can get painful if you need to do it for many different
types, and downright impossible if the class in question is
a template. In such cases, one common solution is to use
a Thread object, along the lines of:
class Thread
{
public:
virtual void* run() = 0;
};
and a starter function:
namespace {
extern "C" void*
doStartThread( void* p )
{
return static_cast<Thread*>( p )->run();
}
}
pthread_t
startThread( Thread* thread )
{
pthread_t results;
if ( pthread_create( &results, nullptr, doStartThread, thread ) != 0 ) {
throw std::runtime_error( "Could not create thread" );
}
}
Afterwards, you inherit from Thread, overriding the run
function with whatever you want (and adding any additional data
you might need); the derived class can even be a template.
Again, the lifetime of the Thread object is an issue; the
solution I've usually used has been to require it to be
dynamically allocated, and then delete it at the end of
doStartThread. It's a very good idea to catch it in an
std::unique_ptr in doStartThread, although you still want to
catch exceptions in this function, since otherwise they will
kill the process. And don't forget the delete if
pthread_create fails (since the caller has passed over
ownership. If you really want to be sure:
namespace {
extern "C" void*
doStartThread( void* p )
{
std::unique_ptr<Thread*> object( static_cast<Thread*>( p ) );
try {
return object->run();
} catch ( ... ) {
return somethingElseToReportTheError;
}
}
}
pthread_t
startThread( std::unique_ptr<Thread> thread )
{
pthread_t results;
if ( pthread_create( &results, nullptr, doStartThread, thread.get() ) != 0 ) {
throw std::runtime_error( "Could not create thread" );
}
thread.release(); // AFTER the call has succeeded!
}
I've used this technique successfully in a number of
applications (using std::auto_ptr, since there was no
std::unique_ptr then); typically, the fact that you need to
use dynamic allocation is not an issue, and it solves the
lifetime issue quite nicely. (The alternative would be to use
a conditional variable, blocking the original thread until the
new thread had copied everything over.)
Note that by using a unique_ptr in the interface, you
effectively block the calling thread from further access to the
thread object, by robbing it of its pointer to the object. This
offers an additional guarantee with regards to thread safety.
But of course, this additional guarantee (and the solution to
the lifetime issues) only applies to the Thread object itself,
and not to anything it might point to.

std::thread : how to declare a thread in class body as a normal member?

I want to have a thread for each instance of Page object. At a time only one of them can execute (simply checks if pointer to current running thread is joinable or not..)
class Page : public std::vector<Step>
{
// ....
void play();
void start(); // check if no other thread is running. if there is a running thread, return. else join starter
std::thread starter; // std::thread running this->play()
static std::thread* current; // pointer to current running thread
// ...
};
I want to be able to fire-up starter threads of Page objects. for example like this:
Page x , y , z;
// do some stuff for initialize pages..
x.start();
// do some other work
y.start(); // if x is finished, start y otherwise do nothing
// do some other lengthy work
z.start(); // if x and y are not running, start z
I can't manage to declare started as a member of Page. I found that it's because of the fact std::threads can only initialized at declaration time. (or something like that, cause it's not possible to copy a thread)
void x()
{
}
//...
std::thread t(x); // this is ok
std::thread r; // this is wrong, but I need this !
r = std::thread(this->y); // no hope
r = std::thread(y); // this is wrong too
You can initialize the thread to the function to run by using a member initializer list. For example, consider this constructor for Page:
class Page {
public:
Page(); // For example
private:
std::thread toRun;
};
Page::Page() : toRun(/* function to run */) {
/* ... */
}
Notice how we use the initialization list inside the Page constructor to initialize toRun to the function that ought to be run. This way, toRun is initialized as if you had declared it as a local variable
std::string toRun(/* function to run */);
That said, there are two major problems I think that you must address in your code. First, you should not inherit from std::vector or any of the standard collections classes. Those classes don't have their destructors marked virtual, which means that you can easily invoke undefined behavior if you try to treat your Page as a std::vector. Instead, consider making Page hold a std::vector as a direct subobject. Also, you should not expose the std::thread member of the class. Data members should, as a general rule, be private to increase encapsulation, make it easier to modify the class in the future, and prevent people from breaking all of your class's invariants.
Hope this helps!
Never publicly inherit from a std container, unless the code is meant to be throw away code. An honestly it's terrifying how often throw away code becomes production code when push comes to shove.
I understand you don't want to reproduce the whole std::vector interface. That is tedious write, a pain to maintain, and honestly could create bugs.
Try this instead
class Page: private std::vector
{
public:
using std::vector::push_back;
using std::vector::size;
// ...
};
Ignoring the std::vector issue this should work for the concurrency part of the problem.
class Page
{
~Page( void )
{
m_thread.join();
}
void start( void );
private:
// note this is private, it must be to maintain the s_running invariant
void play( void )
{
assert( s_current == this );
// Only one Page at a time will execute this code.
std::lock_guard<std::mutex> _{ s_mutex };
s_running = nullptr;
}
std::thread m_thread;
static Page* s_running;
static std::mutex s_mutex;
};
Page* Page::s_running = nullptr;
std::mutex Page::s_mutex;
std::condition Page::s_condition;
void Page::start( void )
{
std::lock_guard<std::mutex> _{ s_mutex };
if( s_running == nullptr )
{
s_running = this;
m_thread = std::thread{ [this](){ this->play(); } };
}
}
This solution is may have initialization order issues if Page is instantiate before main()

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.

c++ multithread

I use C++ to implement a thread class. My code shows in the following.
I have a problem about how to access thread data.
In the class Thread, I create a thread use pthread_create() function. then it calls EntryPoint() function to start thread created. In the Run function, I want to access the mask variable, it always shows segment fault.
So, my question is whether the new created thread copy the data in original class? How to access the thread own data?
class Thread {
public:
int mask;
pthread_t thread;
Thread( int );
void start();
static void * EntryPoint (void *);
void Run();
};
Thread::Thread( int a) {
mask =a;
}
void Thread::Run() {
cout<<"thread begin to run" <<endl;
cout << mask <<endl; // it always show segmentfault here
}
void * Thread::EntryPoint(void * pthis) {
cout << "entry" <<endl;
Thread *pt = (Thread *) pthis;
pt->Run();
}
void Thread::start() {
pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
pthread_join(thread, NULL);
}
int main() {
int input_array[8]={3,1,2,5,6,8,7,4};
Thread t1(1);
t1.start();
}
I'm not familiar with the libraries you're using, but how does EntryPoint know that pthis is a pointer to Thread? Thread (this) does not appear to be passed to pthread_create.
It's great that you're attempting to write a Thread class for educational purposes. However, if you're not, why reinvent the wheel?
pThis is most likely NULL, you should double check that you're passing the correct arguments to pthread_create.
Basically, the problem is as soon as you start your thread, main exits and your local Thread instance goes out of scope. So, because the lifetime of your thread object is controlled by another thread, you've already introduced a race condition.
Also, I'd consider joining a thread immediately after you've created it in Thread::start to be a little odd.