Today I want to use a boost::scoped_ptr to point to a boost::thread.
In my Thread.h I have boost::scoped_ptr<boost::thread> m_thread and in my Thread.cpp there's a function create() in which the creation of the boost::thread should take place.
I tried Thread::m_thread (new boost::thread(attr, boost::bind(%Thread::run, this))); but unsurprisingly it didn't work.
I can't figure out myself (or by using the boost documentation) how I would do this, since I don't fully understand what's happening with the scoped_ptr and how it works.
Before I used to use a raw pointer, which worked fine but I'm not allowed to use it at this point.
Thanks for your time!
I don't know what kind of error your got, try this:
class Thread {
public:
Thread() : thread_(new boost::thread(boost::bind(&Thread::run, this))) {
}
void run() {
}
~Thread() {
thread_->join();
}
private:
boost::scoped_ptr<boost::thread> thread_;
};
int main() {
Thread thread;
}
But do not forget, that thread may start before constructor end his job.
Related
In C++20 std::jthread was introduced as a safer version of std::thread; where std::jthread, as far as I understand, cleans up after itself when the thread exits.
Also, the concept of cooperative cancellation is introduced such that an std::jthread manages an std::stop_source that handles the state of the underlying thread, this std::stop_source exposes an std::stop_token that outsiders can use to read the state of the thread sanely.
What I have is something like this.
class foo {
std::stop_token stok;
std::stop_source ssource;
public:
void start_foo() {
// ...
auto calculation = [this](std::stop_token inner_tok) {
// ... (*this is used here)
while(!inner_tok.stop_requested()) {
// stuff
}
}
auto thread = std::jthread(calculation);
ctok = thread.get_stop_token();
ssource = thread.get_stop_source();
thread.detach(); // ??
}
void stop_foo() {
if (ssource.stop_possible()) {
ssource.request_stop();
}
}
~foo() {
stop_foo();
}
}
Note foo is managed by a std::shared_ptr, and there is no public constructor.
Somewhere along the line, another thread can call foo::stop_foo() on a possibly detached thread.
Is what I am doing safe?
Also, when detaching a thread, the C++ handle is no longer associated with the running thread, and the OS manages it, but does the thread keep receiving stop notifications from the std::stop_source?
Is there a better way to achieve what I need? In MVSC, this doesn't seem to raise any exceptions or halt program execution, and I've done a lot of testing to verify this.
So, is this solution portable?
What you wrote is potentially unsafe if the thread accesses this after the foo has been destroyed. It's also a bit convoluted. A simpler approach would just be to stick the jthread in the structure...
class foo {
std::jthread thr;
public:
void start_foo() {
// ...
jthr = std::jthread([this](std::stop_token inner_tok) {
// ... (*this is used here)
while(!inner_tok.stop_requested()) {
// stuff
}
});
}
void stop_foo() {
jthr.request_stop();
}
~foo() {
stop_foo();
// jthr.detatch(); // this is a bad idea
}
}
To match the semantics of your code, you would uncomment the jthr.detach() in the destructor, but this is actually a bad idea since then you could end up destroying foo while the thread is still accessing it. The code I wrote above is safe, but obviously whichever thread drops the last reference to the foo will have to wait for the jthread to exit. If that's really intolerable, then maybe you want to change the API to stick a shared_ptr in the thread itself, so that the thread can destroy foo if it is still running after the last external reference is dropped.
std::thread::join does not return, even if the thread routine is exited.
Guess, I have a class.
class A
{
public:
A()
{
this->thr = std::thread(&A::foo, this);
}
~A()
{
this->join();
}
void join()
{
this->cond.notify_all();
if (this->thr.joinable())
{
this->thr.join();
}
}
private:
void foo()
{
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
this->cond.wait(lck);
MessageBox(L"I'm done!");
}
private:
std::thread thr;
std::condition_variable cond;
};
My application contains the only instance of A. It is a global variable.
If A::join is called from the destructor, std::thread::join blocks forever.
If I call A::join manually (e.g. before exiting main), everything is alright.
My main looks like this:
A a;
int main()
{
auto timeout = std::chrono::seconds(3);
std::this_thread::sleep_for(timeout);
// a.join();
}
By the way, MessageBox is always executed.
Is that the same problem as here?
Yes it is the same bug as in the referenced link since your example also hangs on _Thrd_join. You could be interrested in this question which contains a far more detailed analysis.
from your comment
"It doesn't seem to be a great solution. I works, but what if the main
is not so trivial? There're a lot of different ways of exiting from my
application. Thus, I've got to join my threads manually every time I
need it?"
how about making A a std::unique_ptr within your main. that way, no matter how your main exits, it'll always destroy A before exiting main() and you won't have this problem.
I have a server-type application, and I have an issue with making sure thread's aren't deleted before they complete. The code below pretty much represents my server; the cleanup is required to prevent a build up of dead threads in the list.
using namespace std;
class A {
public:
void doSomethingThreaded(function<void()> cleanupFunction, function<bool()> getStopFlag) {
somethingThread = thread([cleanupFunction, getStopFlag, this]() {
doSomething(getStopFlag);
cleanupFunction();
});
}
private:
void doSomething(function<bool()> getStopFlag);
thread somethingThread;
...
}
class B {
public:
void runServer();
void stop() {
stopFlag = true;
waitForListToBeEmpty();
}
private:
void waitForListToBeEmpty() { ... };
void handleAccept(...) {
shared_ptr<A> newClient(new A());
{
unique_lock<mutex> lock(listMutex);
clientData.push_back(newClient);
}
newClient.doSomethingThreaded(bind(&B::cleanup, this, newClient), [this]() {
return stopFlag;
});
}
void cleanup(shared_ptr<A> data) {
unique_lock<mutex> lock(listMutex);
clientData.remove(data);
}
list<shared_ptr<A>> clientData;
mutex listMutex;
atomc<bool> stopFlag;
}
The issue seems to be that the destructors run in the wrong order - i.e. the shared_ptr is destructed at when the thread's function completes, meaning the 'A' object is deleted before thread completion, causing havok when the thread's destructor is called.
i.e.
Call cleanup function
All references to this (i.e. an A object) removed, so call destructor (including this thread's destructor)
Call this thread's destructor again -- OH NOES!
I've looked at alternatives, such as maintaining a 'to be removed' list which is periodically used to clean the primary list by another thread, or using a time-delayed deletor function for the shared pointers, but both of these seem abit chunky and could have race conditions.
Anyone know of a good way to do this? I can't see an easy way of refactoring it to work ok.
Are the threads joinable or detached? I don't see any detach,
which means that destructing the thread object without having
joined it is a fatal error. You might try simply detaching it,
although this can make a clean shutdown somewhat complex. (Of
course, for a lot of servers, there should never be a shutdown
anyway.) Otherwise: what I've done in the past is to create
a reaper thread; a thread which does nothing but join any
outstanding threads, to clean up after them.
I might add that this is a good example of a case where
shared_ptr is not appropriate. You want full control over
when the delete occurs; if you detach, you can do it in the
clean up function (but quite frankly, just using delete this;
at the end of the lambda in A::doSomethingThreaded seems more
readable); otherwise, you do it after you've joined, in the
reaper thread.
EDIT:
For the reaper thread, something like the following should work:
class ReaperQueue
{
std::deque<A*> myQueue;
std::mutex myMutex;
std::conditional_variable myCond;
A* getOne()
{
std::lock<std::mutex> lock( myMutex );
myCond.wait( lock, [&]( !myQueue.empty() ) );
A* results = myQueue.front();
myQueue.pop_front();
return results;
}
public:
void readyToReap( A* finished_thread )
{
std::unique_lock<std::mutex> lock( myMutex );
myQueue.push_back( finished_thread );
myCond.notify_all();
}
void reaperThread()
{
for ( ; ; )
{
A* mine = getOne();
mine->somethingThread.join();
delete mine;
}
}
};
(Warning: I've not tested this, and I've tried to use the C++11
functionality. I've only actually implemented it, in the past,
using pthreads, so there could be some errors. The basic
principles should hold, however.)
To use, create an instance, then start a thread calling
reaperThread on it. In the cleanup of each thread, call
readyToReap.
To support a clean shutdown, you may want to use two queues: you
insert each thread into the first, as it is created, and then
move it from the first to the second (which would correspond to
myQueue, above) in readyToReap. To shut down, you then wait
until both queues are empty (not starting any new threads in
this interval, of course).
The issue is that, since you manage A via shared pointers, the this pointer captured by the thread lambda really needs to be a shared pointer rather than a raw pointer to prevent it from becoming dangling. The problem is that there's no easy way to create a shared_ptr from a raw pointer when you don't have an actual shared_ptr as well.
One way to get around this is to use shared_from_this:
class A : public enable_shared_from_this<A> {
public:
void doSomethingThreaded(function<void()> cleanupFunction, function<bool()> getStopFlag) {
somethingThread = thread([cleanupFunction, getStopFlag, this]() {
shared_ptr<A> temp = shared_from_this();
doSomething(getStopFlag);
cleanupFunction();
});
this creates an extra shared_ptr to the A object that keeps it alive until the thread finishes.
Note that you still have the problem with join/detach that James Kanze identified -- Every thread must have either join or detach called on it exactly once before it is destroyed. You can fulfill that requirement by adding a detach call to the thread lambda if you never care about the thread exit value.
You also have potential for problems if doSomethingThreaded is called multiple times on a single A object...
For those who are interested, I took abit of both answers given (i.e. James' detach suggestion, and Chris' suggestion about shared_ptr's).
My resultant code looks like this and seems neater and doesn't cause a crash on shutdown or client disconnect:
using namespace std;
class A {
public:
void doSomething(function<bool()> getStopFlag) {
...
}
private:
...
}
class B {
public:
void runServer();
void stop() {
stopFlag = true;
waitForListToBeEmpty();
}
private:
void waitForListToBeEmpty() { ... };
void handleAccept(...) {
shared_ptr<A> newClient(new A());
{
unique_lock<mutex> lock(listMutex);
clientData.push_back(newClient);
}
thread clientThread([this, newClient]() {
// Capture the shared_ptr until thread over and done with.
newClient->doSomething([this]() {
return stopFlag;
});
cleanup(newClient);
});
// Detach to remove the need to store these threads until their completion.
clientThread.detach();
}
void cleanup(shared_ptr<A> data) {
unique_lock<mutex> lock(listMutex);
clientData.remove(data);
}
list<shared_ptr<A>> clientData; // Can remove this if you don't
// need to connect with your clients.
// However, you'd need to make sure this
// didn't get deallocated before all clients
// finished as they reference the boolean stopFlag
// OR make it a shared_ptr to an atomic boolean
mutex listMutex;
atomc<bool> stopFlag;
}
I create a thread in a class member method like this:
void MyClass::startThread()
{
T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
}
void MyClass::myThreadMethod()
{
// ...
}
where
// In header file
std::unique_ptr<std::thread> T;
When I run MyClass::startThread(), I receive this:
Signal received: SIGABRT (Aborted) ...
If I step the code, it happens in the thread constructor.
I tried to removed the unique_ptr like this:
void MyClass::startThread()
{
std::thread* T = new std::thread( &MyClass::myThreadMethod, this );
}
and the same thing occurred. I use gcc 4.8.2 on NetBeans 7.4 on Linux/Kubuntu 12.04.
Someone knows what happens?
This happens when an std::thread is destroyed without a prior call to std::thread::detach() or std::thread::join(). You should call either of the two, and what to call depends on your desired behavior.
void MyClass::startThread() {
T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
T->join(); // Wait for thread to finish
}
or
void MyClass::startThread() {
T.reset( new std::thread( &MyClass::myThreadMethod, this ) );
T->detach(); // Leave thread on its own (do not wait for it to finish)
}
As a side note, you can remove your use of std::unique_ptr by making the std::thread itself a member:
class MyClass {
std::thread t;
};
To assign t a thread, you can construct one and move assign it to t:
t = std::thread(&MyClass::myThreadMethod, this);
According to Mark Garcia suggestion and example, and according to this question I just added -pthread as option to the compiler.
For an unknown reason, my other projects work correctly but I believe that it is due to Boost or Open CV that must include something that was missing from this current test.
Anyway, for the moment, it works.
Thanks!
After searching trough the forum, i came across some answers nevertheles I could not get a clear answer to how to run a static method in a new thread in c++. My main concern is what is the best way to start a thread?(Is it working also from inside of another thread?)
which header is better to use? thread.h, pthread.h?
I would like to create a new thread(when a given method is called) and call inside this thread another function...
Any hints how I could approach this issue?
Thank you guys very much in advance!
There is no problem to run static member function in thread. Just use std::thread the same way as for free function:
#include <thread>
class Threaded
{
public:
static void thread_func() {}
};
int main()
{
std::thread t(Threaded::thread_func);
t.join();
return 0;
}
Of course, starting thread will work from any other thread as well. With C++11 standard compliant compiler you shall use #include <thread>. Otherwise take a look at boost::thread. It's usage is similar.
Assuming for example your static function has two parameters:
#include <boost/thread/thread.hpp>
void launchThread()
{
boost::thread t( &MyClass::MyStaticFunction, arg1, arg2 );
}
This will require linking to the Boost.Thread library.
The best OOPs way of doing this would be:
Define an entry point (entryPoint()) which will call a member function(myThreadproc()). The entry point will start the thread and call myThreadproc. Then you can access all the member variables and methods.
myClassA.h
class A
{
static void *entryPoint(void *arg);
void myThreadproc();
void myfoo1();
void myfoo2();
}
myClassA.cpp
void *A::entryPoint(void *arg)
{
A *thisClass = (A *)arg;
thisClass-> myThreadproc();
}
void A::myThreadproc()
{
//Now this function is running in the thread..
myfoo1();
myfoo2();
}
Now you can create the thread like this:
int main()
{
pthread_t thread_id;
pthread_create(&thread_id,NULL,(A::entryPoint),new A());
//Wait for the thread
return 0;
}