I have a function (messageArrived) that call's a function (setAnimation) inside a new thread. How can i access a boolean that is defined inside the messageArrived function and access it in the second thread?
If there is a new message i want to terminate the second thread (setAnimation). I fugured that whit a boolean is the only way to "terminate" a thread.
#include <thread>
bool start = false;
void setAnimation(std::string msg){
start = true;
while(start){
//do something
}
return;
}
int messageArrived(std::string message){
start = false;
std::thread t1(setAnimation, message);
t1.detach();
return 1;
}
Above code is just an example to clarify my question.
When creating your thread, you can pass a variable by reference using std::ref However, you would still need to have your variable outside the function, else it will get out of scope.
std::thread t1(setAnimation, message, std::ref(myVariable));
Related
I'm trying to build a thread-safety layer on top of C++ 11's std::thread where each object is assigned to an owning thread, and certain calls can raise a hard error when they are used on the wrong thread. The owning thread is the only one that can transfer an object to another thread.
I have it all working, except that I can't find a way to get a thread's thread::id before it is actually running. And I need to attach the new thread's ID to the object before I hand it off.
If I use
std::thread newThread( [theObject]()
{
// use theObject here.
} );
The earliest point I can get the thread's ID is after the definition of the thread object, at which point the thread is already running.
I see there is a default constructor for std::thread, but I can't see a way to give it a function to run on the thread afterwards.
Is there a way to perform two-step construction on a thread, or control the thread's ID at time of creation?
Rather than getting the ID of the thread before it starts running, you could consider having the function the thread executes do some initial setup before taking off. For example, you could do something like this:
bool isReady = false;
bool wasReceived = false;
std::mutex mutex;
std::condition_variable condition;
std::thread newThread([theObject, &isReady, &mutex, &condition] {
/* Wait until we've been cleared to go. */
std::unique_lock<std::mutex> lock(isReady);
condition.wait(lock, [&isReady] { return isReady; });
/* Signal that we're done. */
wasReceived = true;
lock.unlock();
condition.notify_one();
/* Put code here to do whatever it is that the thread should do. */
});
/* Read the thread's ID. It's currently waiting for us. */
auto id = newThread.get_id();
/* Tell the thread that we're ready for it. */
std::unique_lock<std::mutex> lock(mutex);
isReady = true;
condition.notify_one();
/* Wait until the thread has confirmed that it's ready. */
condition.wait(lock, [&] { return wasReceived; });
This creates the thread and has it sit and wait until the creator has a chance to read its ID. Once that's happened, the creator then waits until the thread confirms that it's ready to go, and from there you can work with the thread ID however you'd like.
Beware of bugs in the above code - it's completely untested. :-)
No--as soon as you create a thread, it starts to run. If you want to get its ID before it does (much of) anything, you probably want to create a little wrapper, where you pass the thread (for example) a CV and a queue where it deposits its output.
Then when the thread starts up, it retrieves its own ID, deposits it in the output queue, and then waits on the CV. When the parent has retrieved the ID, and is ready for the child to start doing something, it signals the CV, and off it goes.
Start each thread inactived by passing a unique std::promise parameter, get the thread id first ( thread id is used as a pass by reference parameter for the purpose) afterwards let it wait for the promise to be set by the thread manager. This will also remove the hassle of using a conditional variable.
Edited Snippet
class smart_thread {
public:
smart_thread(std::function<void(void)> task)
{
thread_ = std::thread([=]() {
id_ = std::this_thread::get_id();
// wait here till activated
future_.get();
if(active_) task();
});
}
void activate() {
promise_.set_value();
active_ = true;
}
~smart_thread() {
if(!active_) promise_.set_value();
thread_.join();
}
private:
std::thread::id id_;
std::atomic<bool> active_ = false;
std::thread thread_;
std::promise<void> promise_;
std::future<void> future_ = promise_.get_future();
};
void main()
{
auto task = []() { std::cout << "Hello World\n"; };
smart_thread thread(task); // start thread inactive mode
thread.activate(); // activate thread
}
Would it be possible to create a template class that accepts the thread routine in the form of a std::function<void(T *object)>. This can easily be done with an anonymous closure if additional parameters need to be passed in.
template <class T>
class ThreadWrapper
{
public:
ThreadWrapper(std::function<void(T *object)> function, T *object) :
{
m_thread = std::thread(WrapFunction, function, object);
//optionally
m_thread.detach();
}
static void WrapFunction(ThreadWrapper *wrapper, std::function<void()> function, T *object)
{
// Get the thread id and save in the object
object->SetThreadId(get_id());
// Now actually invoke the thread routine, with the id already installed.
function(object);
}
}
// Cleanup is left as an exercise for the reader.
Beware of bugs in the above code - it's completely untested. :-) :-)
I'm getting into C++11 threads and have run into a problem.
I want to declare a thread variable as global and start it later.
However all the examples I've seen seem to start the thread immediately for example
thread t(doSomething);
What I want is
thread t;
and start the thread later.
What I've tried is
if(!isThreadRunning)
{
thread t(readTable);
}
but now t is block scope. So I want to declare t and then start the thread later so that t is accessible to other functions.
Thanks for any help.
std::thread's default constructor instantiates a std::thread without starting or representing any actual thread.
std::thread t;
The assignment operator moves the state of a thread object, and sets the assigned-from thread object to its default-initialized state:
t = std::thread(/* new thread code goes here */);
This first constructs a temporary thread object representing a new thread, transfers the new thread representation into the existing thread object that has a default state, and sets the temporary thread object's state to the default state that does not represent any running thread. Then the temporary thread object is destroyed, doing nothing.
Here's an example:
#include <iostream>
#include <thread>
void thread_func(const int i) {
std::cout << "hello from thread: " << i << std::endl;
}
int main() {
std::thread t;
std::cout << "t exists" << std::endl;
t = std::thread{ thread_func, 7 };
t.join();
std::cout << "done!" << std::endl;
}
As antred says in his answer, you can use a condition variable to make the thread to wait in the beginning of its routine.
Scott Meyers in his book “Effective Modern C++” (in the “Item 39: Consider void futures for one-shot event communication”) proposes to use void-future instead of lower level entities (boolean flag, conditional variable and mutex). So the problem can be solved like this:
auto thread_starter = std::promise<void>;
auto thread = std::thread([starter_future = thread_starter.get_future()]() mutable {
starter_future.wait(); //wait before starting actual work
…; //do actual work
});
…; //you can do something, thread is like “paused” here
thread_starter.set_value(); //“start” the thread (break its initial waiting)
Scott Meyers also warns about exceptions in the second … (marked by the you can do something, thread is like “paused” here comment). If thread_starter.set_value() is never called for some reasons (for example, due to exception throws in the second …), the thread will wait forever, and any attempt to join it would result in deadlock.
As both ways (condvar-based and future-based) contain hidden unsafety, and the first way (condvar-based) needs some boilerplate code, I propose to write a wrapper class around std::thread. Its interface should be similar to the one of std::thread (except that its instances should be assignable from other instances of the same class, not from std::thread), but contain additional void start() method.
Future-based thread-wrapper
class initially_suspended_thread {
std::promise<bool> starter;
std::thread impl;
public:
template<class F, class ...Args>
explicit initially_suspended_thread(F &&f, Args &&...args):
starter(),
impl([
starter_future = starter.get_future(),
routine = std::bind(std::forward<F>(f), std::forward<Args>(args)...)
]() mutable {if (starter_future.get()) routine();})
{}
void start() {starter.set_value(true);}
~initially_suspended_thread() {
try {starter.set_value(false);}
catch (const std::future_error &exc) {
if (exc.code() != std::future_errc::promise_already_satisfied) throw;
return; //already “started”, no need to do anything
}
impl.join(); //auto-join not-yet-“started” threads
}
…; //other methods, trivial
};
Condvar-based thread-wrapper
class initially_suspended_thread {
std::mutex state_mutex;
enum {INITIAL, STARTED, ABORTED} state;
std::condition_variable state_condvar;
std::thread impl;
public:
template<class F, class ...Args>
explicit initially_suspended_thread(F &&f, Args &&...args):
state_mutex(), state(INITIAL), state_condvar(),
impl([
&state_mutex = state_mutex, &state = state, &state_condvar = state_condvar,
routine = std::bind(std::forward<F>(f), std::forward<Args>(args)...)
]() {
{
std::unique_lock state_mutex_lock(state_mutex);
state_condvar.wait(
state_mutex_lock,
[&state]() {return state != INITIAL;}
);
}
if (state == STARTED) routine();
})
{}
void start() {
{
std::lock_guard state_mutex_lock(state_mutex);
state = STARTED;
}
state_condvar.notify_one();
}
~initially_suspended_thread() {
{
std::lock_guard state_mutex_lock(state_mutex);
if (state == STARTED) return; //already “started”, no need to do anything
state = ABORTED;
}
impl.join(); //auto-join not-yet-“started” threads
}
…; //other methods, trivial
};
There is no "standard" of creating a thread "suspended" which I assume is what you wanted to do with the C++ thread library. Because it is not supported on every platform that has threads, it is not there in the C++ API.
You might want to create a class with all the data it is required but not actually run your thread function. This is not the same as creating the thread but may be what you want. If so, create that, then later bind the object and its operator() or start() function or whatever to the thread.
You might want the thread id for your thread. That means you do actually need to start the thread function. However it can start by waiting on a condition variable. You then signal or broadcast to that condition variable later when you want it to continue running. Of course you can have the function check a condition after it resumes in case you might have decided to close it and not run it after all (in which case it will just return instantly).
You might want a std::thread object with no function. You can do that and attach it to a function later to run that function in a new thread.
I would give the thread a condition variable and a boolean called startRunning (initially set to false). Effectively you would start the thread immediately upon creation, but the first thing it would do is suspend itself (using the condition_variable) and then only begin processing its actual task when the condition_variable is signaled from outside (and the startRunning flag set to true).
EDIT: PSEUDO CODE:
// in your worker thread
{
lock_guard l( theMutex );
while ( ! startRunning )
{
cond_var.wait( l );
}
}
// now start processing task
// in your main thread (after creating the worker thread)
{
lock_guard l( theMutex );
startRunning = true;
cond_var.signal_one();
}
EDIT #2: In the above code, the variables theMutex, startRunning and cond_var must be accessible by both threads. Whether you achieve that by making them globals or by encapsulating them in a struct / class instance is up to you.
first declared in class m_grabber runs nothing. We assign member class object with new one with lambda function in launch_grabber method and thread with lambda runs within source class context.
class source {
...
std::thread m_grabber;
bool m_active;
...
}
bool source::launch_grabber() {
// start grabber
m_grabber = std::thread{
[&] () {
m_active = true;
while (true)
{
if(!m_active)
break;
// TODO: something in new thread
}
}
};
m_grabber.detach();
return true;
}
You could use singleton pattern. Or I would rather say antipattern.
Inside a singleton you would have std::thread object encapsulated. Upon first access to singleton your thread will be created and started.
I'm getting into C++11 threads and have run into a problem.
I want to declare a thread variable as global and start it later.
However all the examples I've seen seem to start the thread immediately for example
thread t(doSomething);
What I want is
thread t;
and start the thread later.
What I've tried is
if(!isThreadRunning)
{
thread t(readTable);
}
but now t is block scope. So I want to declare t and then start the thread later so that t is accessible to other functions.
Thanks for any help.
std::thread's default constructor instantiates a std::thread without starting or representing any actual thread.
std::thread t;
The assignment operator moves the state of a thread object, and sets the assigned-from thread object to its default-initialized state:
t = std::thread(/* new thread code goes here */);
This first constructs a temporary thread object representing a new thread, transfers the new thread representation into the existing thread object that has a default state, and sets the temporary thread object's state to the default state that does not represent any running thread. Then the temporary thread object is destroyed, doing nothing.
Here's an example:
#include <iostream>
#include <thread>
void thread_func(const int i) {
std::cout << "hello from thread: " << i << std::endl;
}
int main() {
std::thread t;
std::cout << "t exists" << std::endl;
t = std::thread{ thread_func, 7 };
t.join();
std::cout << "done!" << std::endl;
}
As antred says in his answer, you can use a condition variable to make the thread to wait in the beginning of its routine.
Scott Meyers in his book “Effective Modern C++” (in the “Item 39: Consider void futures for one-shot event communication”) proposes to use void-future instead of lower level entities (boolean flag, conditional variable and mutex). So the problem can be solved like this:
auto thread_starter = std::promise<void>;
auto thread = std::thread([starter_future = thread_starter.get_future()]() mutable {
starter_future.wait(); //wait before starting actual work
…; //do actual work
});
…; //you can do something, thread is like “paused” here
thread_starter.set_value(); //“start” the thread (break its initial waiting)
Scott Meyers also warns about exceptions in the second … (marked by the you can do something, thread is like “paused” here comment). If thread_starter.set_value() is never called for some reasons (for example, due to exception throws in the second …), the thread will wait forever, and any attempt to join it would result in deadlock.
As both ways (condvar-based and future-based) contain hidden unsafety, and the first way (condvar-based) needs some boilerplate code, I propose to write a wrapper class around std::thread. Its interface should be similar to the one of std::thread (except that its instances should be assignable from other instances of the same class, not from std::thread), but contain additional void start() method.
Future-based thread-wrapper
class initially_suspended_thread {
std::promise<bool> starter;
std::thread impl;
public:
template<class F, class ...Args>
explicit initially_suspended_thread(F &&f, Args &&...args):
starter(),
impl([
starter_future = starter.get_future(),
routine = std::bind(std::forward<F>(f), std::forward<Args>(args)...)
]() mutable {if (starter_future.get()) routine();})
{}
void start() {starter.set_value(true);}
~initially_suspended_thread() {
try {starter.set_value(false);}
catch (const std::future_error &exc) {
if (exc.code() != std::future_errc::promise_already_satisfied) throw;
return; //already “started”, no need to do anything
}
impl.join(); //auto-join not-yet-“started” threads
}
…; //other methods, trivial
};
Condvar-based thread-wrapper
class initially_suspended_thread {
std::mutex state_mutex;
enum {INITIAL, STARTED, ABORTED} state;
std::condition_variable state_condvar;
std::thread impl;
public:
template<class F, class ...Args>
explicit initially_suspended_thread(F &&f, Args &&...args):
state_mutex(), state(INITIAL), state_condvar(),
impl([
&state_mutex = state_mutex, &state = state, &state_condvar = state_condvar,
routine = std::bind(std::forward<F>(f), std::forward<Args>(args)...)
]() {
{
std::unique_lock state_mutex_lock(state_mutex);
state_condvar.wait(
state_mutex_lock,
[&state]() {return state != INITIAL;}
);
}
if (state == STARTED) routine();
})
{}
void start() {
{
std::lock_guard state_mutex_lock(state_mutex);
state = STARTED;
}
state_condvar.notify_one();
}
~initially_suspended_thread() {
{
std::lock_guard state_mutex_lock(state_mutex);
if (state == STARTED) return; //already “started”, no need to do anything
state = ABORTED;
}
impl.join(); //auto-join not-yet-“started” threads
}
…; //other methods, trivial
};
There is no "standard" of creating a thread "suspended" which I assume is what you wanted to do with the C++ thread library. Because it is not supported on every platform that has threads, it is not there in the C++ API.
You might want to create a class with all the data it is required but not actually run your thread function. This is not the same as creating the thread but may be what you want. If so, create that, then later bind the object and its operator() or start() function or whatever to the thread.
You might want the thread id for your thread. That means you do actually need to start the thread function. However it can start by waiting on a condition variable. You then signal or broadcast to that condition variable later when you want it to continue running. Of course you can have the function check a condition after it resumes in case you might have decided to close it and not run it after all (in which case it will just return instantly).
You might want a std::thread object with no function. You can do that and attach it to a function later to run that function in a new thread.
I would give the thread a condition variable and a boolean called startRunning (initially set to false). Effectively you would start the thread immediately upon creation, but the first thing it would do is suspend itself (using the condition_variable) and then only begin processing its actual task when the condition_variable is signaled from outside (and the startRunning flag set to true).
EDIT: PSEUDO CODE:
// in your worker thread
{
lock_guard l( theMutex );
while ( ! startRunning )
{
cond_var.wait( l );
}
}
// now start processing task
// in your main thread (after creating the worker thread)
{
lock_guard l( theMutex );
startRunning = true;
cond_var.signal_one();
}
EDIT #2: In the above code, the variables theMutex, startRunning and cond_var must be accessible by both threads. Whether you achieve that by making them globals or by encapsulating them in a struct / class instance is up to you.
first declared in class m_grabber runs nothing. We assign member class object with new one with lambda function in launch_grabber method and thread with lambda runs within source class context.
class source {
...
std::thread m_grabber;
bool m_active;
...
}
bool source::launch_grabber() {
// start grabber
m_grabber = std::thread{
[&] () {
m_active = true;
while (true)
{
if(!m_active)
break;
// TODO: something in new thread
}
}
};
m_grabber.detach();
return true;
}
You could use singleton pattern. Or I would rather say antipattern.
Inside a singleton you would have std::thread object encapsulated. Upon first access to singleton your thread will be created and started.
After using threads for a while, I got into a situation where I needed a thread to run forever until a a function (or any sort of event) was called. To do this I created a bool value to control a while loop inside the function that was executed by the thread, but I quickly noticed that external variables are not updated after a thread starts running, causing the thread to never stop when it was asked to.
Heres some simple code to represent the issue:
#include <cstdio>
#include <thread>
#include <chrono>
class A {
public:
A();
void startThread();
void endThread();
private:
void threadCall();
bool active;
};
int main() {
A threadThing;
threadThing.startThread();
printf("[M] Thread Created\n");
std::this_thread::sleep_for(std::chrono::seconds(5));
threadThing.endThread();
printf("[M] Thread Killed\n");
std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;
}
A::A() {
active = false;
}
void A::startThread() {
active = true;
std::thread AThread(&A::threadCall, *this);
AThread.detach();
}
void A::endThread() {
active = false;
}
void A::threadCall() {
printf("[T] Thread Started\n");
while (active) {
std::this_thread::sleep_for(std::chrono::seconds(2));
}
printf("[T] Thread Ended\n");
}
The expected result of this would be that the main function starts the thread, the thread says it started, then 4 seconds later the thread is killed and the thread says it ended, when in reality the thread never says it ends. Is there a way to let the thread access the 'active' variable, or is my approach to this problem incorrect altogether? (Side note, I did try to figure this out on my own but only got stuff like local thread storage which seems like its only for storage inside of threads, not access to the outside but I could be wrong)
The problem is with the constructor of std::thread, it copies/moves by default.
std::thread AThread(&A::threadCall, *this);
this copies the object into the new thread, so checking the active variable in the new object has no effect.
you can remove the *
std::thread AThread(&A::threadCall, this);
you pass the object pointer into the new thread, it will call like the method like this(*this).threadCall().
Edit: as the comments say, this is not guarantee to be thread safe, you need to use std::atomic<bool> to be safe.
What you need to do is pass an A class pointer as an argument to your function that is your thread.
void A::startThread()
{
active = true;
std::thread AThread(threadCall, this);
AThread.detach();
}
void A::threadCall(A *aClass)
{
printf("[T] Thread Started\n");
while (aClass->active)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
}
printf("[T] Thread Ended\n");
}
I need to start a loop from an event and then stop it from another event.
My idea was to call the function startDequeuing() when I press the button so that a thread with the loop start and then to terminate this loop putting "dequeuing" variable at false from the function stopDequeuing().
It's the first time I use thread, the program locks when I start the loop I think because the variable 'dequeuing' is locked and inaccessible from outside the thread, am I correct?
How can I solve this problem??
Here there is some code:
void CameraManager::startDequeuing(){
dequeuing = true;
std::thread dequeueThread(&CameraManager::dequeueLoop, this);
dequeueThread.join();
}
void CameraManager::stopDequeuing(){
dequeuing = false;
}
void *CameraManager::dequeueLoop(){
while(dequeuing){
highSpeedCamera->dequeue();
highSpeedCamera->enqueue();
}
}
The whole point of using threads is to get more than one function running in parallel. Here:
std::thread dequeueThread(&CameraManager::dequeueLoop, this);
dequeueThread.join();
You start a second thread and put the first thread to sleep, waiting for the spawned thread to return. So you still have just one thread running. If you have so kind of GUI event loop, you might lock for a possibility to add a callback that will get called, when ever that event loop is empty. This might enable you to do what you want without using threads at all.
A solution might look like this:
void CameraManager::startDequeuing(){
dequeuing = true;
dequeueThread = std::thread(&CameraManager::dequeueLoop, this);
}
void CameraManager::stopDequeuing(){
{
std::lock_guard<std::mutex> lock( mutex );
dequeuing = false;
}
dequeueThread.join();
}
bool CameraManager::keepOnDequeuing()
{
std::lock_guard<std::mutex> lock( mutex );
return dequeuing;
}
void *CameraManager::dequeueLoop(){
while( keepOnDequeuing() ){
highSpeedCamera->dequeue();
highSpeedCamera->enqueue();
}
}
Your program deadlocks because join() will block until your thread function completes; And it will never complete at that point because it's effectively executing while(true).
You want dequeueThread to be a member of your class. Why would you want it to survive only for the scope of startDequeuing?
Define dequeing as an atomic bool:
#include <atomic>
std::atomic_bool dequeing = false;
It's much faster than using a mutex and gets you the same synchronization.