Instantiate threads without running them? - c++

enablePrint = (bool)someArgv; //set via argv in some code, don't worry about this
if (enablePrint) {
std::thread PrinterT(&Printer, 1000);}
//some code that does some stuff
if (enablePrint) {
PrinterT.join();}
produces:
compile error 194:9: error: ‘PrinterT’ was not declared in this scope PrinterT.join();}
I'm aware this is caused by the C++ requirement to declare PrinterT outside of an if block, what I don't know how to do is how do I declare PrinterT without causing it to automatically execute the function code in the thread? I want to be able to make the running of the Printer function contingent on whether it's enabled or not.

std::thread has an operator = that will do the trick. It moves a running thread into another thread variable.
The default constructor will create a std::thread variable that isn't really a thread.
Try something like:
enablePrint = (bool)someArgv; //set via argv in some code, don't worry about this
std::thread PrinterT;
if (enablePrint) {
PrinterT = std::thread(&Printer, 1000);}
//some code that does some stuff
if (enablePrint) {
PrinterT.join();}

Yes, use default std::thread constructor and move semantics.
thread(): http://ru.cppreference.com/w/cpp/thread/thread/thread
operator=(thread&&): http://en.cppreference.com/w/cpp/thread/thread/operator%3D
Example:
#include <iostream>
#include <thread>
int main() {
bool flag = true;
std::thread thread;
if (flag) {
thread = std::thread([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "Thread done\n";
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "Main done\n";
if (flag) {
thread.join();
}
return 0;
}

Related

Creating a class to store threads and calling them

Here is a simplified version of what I am trying to do:
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>
class client {
private:
std::vector<std::thread> threads;
std::atomic<bool> running;
void main() {
while(running) {
std::cout << "main" << std::endl;
}
}
void render() {
while(running) {
std::cout << "render" << std::endl;
}
}
public:
client() {
running = true;
threads.push_back(std::thread(&client::main, this));
threads.push_back(std::thread(&client::render, this));
}
~client() {
running = false;
for(auto& th : threads) th.join();
};
};
int main() {
client c;
std::string inputString;
getline(std::cin, inputString);
return 0;
}
(Note: code has been changed since question was written)
What I am trying to do is create a class that holds threads for the main loop(of the class), rendering, and a couple other things. However I cannot get this simplified version to work. I have tried using mutex to lock and unlock the threads, but didn't seem to help any. I do not know why it is not working, but I suspect that it is a result of the use of this in threads.push_back(std::thread(this->main, this));.
The current structure of the code doesn't have to remain... The only requirement is that uses one of it's own member functions as a thread (and that, that thread is stored in the class). I am not sure if this requires two classes or if my attempt to do it in one class was the correct approach. I have seen many examples of creating an object, and then calling a member that creates threads. I am trying to avoid this and instead create the threads within the constructor.
The problem here is that you do not wait for the threads to end. In main you create c. This then spawns the threads. The next thing to happen is to return which destroys c. When c is destroyed it destroys its members. Now when a thread is destroyed if it has not been joined or detached then std::terminate is called and the program ends
What you need to do is in the destructor, set running to false and then call join on both the threads. This will stop the loop in each thread and allow c to be destructed correctly.
Doing this however brings up another issue. running is not an atomic variable so writing to it while threads are reading it is undefined behavior. We can fin that though by changing running to a std::atomic<bool> which provides synchronization.
I also had to make a change to the thread construction. When you want to use a member function the syntax should be
std::thread(&class_name::function_name, pointer_to_instance_of_class_name, function_parameters)
so in this case it would be
threads.push_back(std::thread(&client::main, this));
threads.push_back(std::thread(&client::render, this));

block the main thread to wait for its child threads

So I have this class:
class foo {
public:
foo() { };
void me1() const {
while(1) {
std::lock_guard<std::mutex> ldock(m);
std::cout << 0;
}
}
void me2() const {
while(1) {
std::lock_guard<std::mutex> ldock(m);
std::cout << 1;
}
}
private:
std::mutex m;
};
Now I want to run this two methods in some two different threads, I do it like this:
int main() {
foo myfoo;
std::thread firstThread(&foo::me1, &myfoo);
std::thread secondThread(&foo::me2, &myfoo);
firstThread.detach();
secondThread.detach();
//while(1) { }
return 0;
}
I don't want to wait for any of this two methods to finish, they will simultaneously run until the main thread will be killed.
Is it ok to have some kind of infinite-loop at the end of main thread? (like the commented while(1) {}).
Or should I call some kinda sleep function?
You need to define an exit condition in your foo::me1() and foo::me2() . If you don't know how to do that, that
sleep(/*number of seconds you want your program to run*/ );
will do just fine.
If you define a termination clause then the bruteforce would be
to expose something like an atomic:
class foo {
public:
std::atomic<int> me1done = false;
std::atomic<int> me2done = false;
foo() { };
void me1() {
while(/* need exit condition here*/) {
std::lock_guard<std::mutex> ldock(m);
std::cout << 0;
}
me1done = true;
}
void me2() {
while(/*need exit condition here*/) {
std::lock_guard<std::mutex> ldock(m);
std::cout << 1;
}
me2done = true;
}
private:
std::mutex m;
};
and then you can check in main by polling every x-seconds.
int main(void)
{
// start your threads and detach
foo myfoo;
std::thread firstThread(&foo::me1, &myfoo);
std::thread secondThread(&foo::me2, &myfoo);
firstThread.detach();
secondThread.detach();
while( not (myfoo.me1done and myfoo.me2done ) )
{
sleep( /* some time */);
}
return 0;
}
If you want to be more elaborate you will have to work with condition variables.
If you want to determine if the two threads have finished your best bet is actually not to detach() the threads but rather join() them before exiting the main thread. That is, you'd kick off both threads and they'll run concurrently and once kicked off you simply join() each. Of course, that assumes that the threads would terminate.
Having a detach()ed thread effectively means you can never be sure if it has finished. That is generally rarely useful and I consider it a mistake that detach() was added to std::thread. However, even with detach()ed thread you can recognize when an objective is achieved without a busy wait. To that end you'd set up suitable variables indicating completion or progress and have them protected by a std::mutex. The main thread would then wait() on a std::condition_variable which gets notify_once()ed by the respective thread upon the completion/progress update which would be done in reasonable intervals. Once all threads have indicated that they are done or have achieved a suitable objective the main() thread can finish.
Using a timer alone is generally not a good approach. The signalling between threads is typically preferable and tends to create a more responsive system. You can still used a timed version of wait() (i.e., wait_until() or wait_for()), e.g., to alert upon suspecting a somehow hung or timed-out thread.
empty infinite loops as while(1) { } are UB.
adding a sleep inside is OK though.
To run infinitely foo::me1/foo::me2, you have several other choices:
int main()
{
foo myfoo;
std::thread firstThread(&foo::me1, &myfoo);
std::thread secondThread(&foo::me2, &myfoo);
firstThread.join(); // wait infinitely as it never ends.
secondThread.join(); // and so never reach
}
or simply use main thread to do one work:
int main()
{
foo myfoo;
std::thread firstThread(&foo::me1, &myfoo);
myfoo.me2(); // work infinitely as it never ends.
firstThread.join(); // and so never reach
}

C++ Thread access issue with class member variables

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");
}

Why does thread.join fail when called in destructor of global variable

I reduced my problematic code to the following. I have a class C that runs a member function on its own thread. In the destructor of C I want to cleanly exit this thread. This works fine as long as c is defined within main (1), but not when it is a global variable (2). In the latter case, I see that the thread function returns but that the t.join() hangs.
#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>
using namespace std;
class C
{
public:
C()
{
stop = false;
t = thread(&C::ThreadFunc, this);
}
~C()
{
stop = true;
cv.notify_all();
if (t.joinable())
{
cout << "joining" << endl;
t.join();
cout << "joined" << endl;
}
}
private:
void ThreadFunc()
{
while (true)
{
unique_lock<mutex> lock(m);
cv.wait(lock, [&]{return stop;});
cout << "returning" << endl;
return;
}
}
thread t;
mutex m;
condition_variable cv;
bool stop;
};
C c; // does *not* work (2)
int _tmain(int argc, _TCHAR* argv[])
{
C c; // does work (1)
return 0;
}
The reason I use a global variable is that it is actually part of a dll. When the destructor is triggered from DllMain on DLL_PROCESS_DETACH, the same problem occurs.
Is there an explanation and a solution to this problem?
It's a deadlock. You are holding a lock that t requires in order to terminate while you are waiting for t to terminate.
Say as part of t's detach process, it makes some calls into the DLL. How can the DLL sensibly handle a request when there is a thread (the thread that called join) that is partially attached to it? Once you start detaching, and until you finish detaching, the DLL is an inconsistent state and cannot sensibly handle thread attach and detach operations.
You really don't want to try to join a thread while your process is in a context you can't control.

Simple example of threading in C++

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
Create a function that you want the thread to execute, for example:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread> to access the std::thread class.)
The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)
The Code
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
On GCC, compile with -std=c++0x -pthread.
This should work for any operating-system, granted your compiler supports this (C++11) feature.
Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in C++0x, which was just nailed down and hasn't yet been implemented.
The problem is somewhat systemic. Technically the existing C++ memory model isn't strict enough to allow for well-defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the C++0x standard on the topic.
Threads Cannot be Implemented as a Library
That said, there are several cross-platform thread C++ libraries that work just fine in practice. The Intel thread building blocks contains a tbb::thread object that closely approximates the C++0x standard and Boost has a boost::thread library that does the same.
oneAPI Threading Building Blocks
Chapter 19. Thread (Boost documentation)
Using boost::thread, you'd get something like:
#include <boost/thread.hpp>
void task1() {
// do stuff
}
void task2() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(task1);
thread thread_2 = thread(task2);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
There is also a POSIX library for POSIX operating systems.
Check for compatibility:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout << msg << std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1, i2;
i1 = pthread_create(&thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create(&thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Compile with -lpthread.
POSIX Threads
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
Class.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
Unless one wants a separate function in the global namespace, we can use lambda functions for creating threads.
One of the major advantage of creating a thread using lambda is that we don't need to pass local parameters as an argument list. We can use the capture list for the same and the closure property of lambda will take care of the lifecycle.
Here is sample code:
int main() {
int localVariable = 100;
thread th { [=]() {
cout << "The value of local variable => " << localVariable << endl;
}};
th.join();
return 0;
}
By far, I've found C++ lambdas to be the best way of creating threads especially for simpler thread functions.
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread &copy);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it.
More information is in the wxThread documentation.