C++ Multithreading methods in an object with infinite loops - c++

I never did any C++ or multithreading before and need help about something.
Let's suppose I have this in my hpp file.
Class Test{
public:
struct type_something_to_kill_the_foo_thread something_to_kill_the_foo_thread;// I don't know what
void foo(stuff stuff){
while(true) does_stuff(stuff);
}
void thread_foo(stuff stuff){
std::thread th = (&Test::foo, this, stuff);
something_to_kill_the_foo_thread = th; // or th.getid() any mechanism so that I can invoke a function to destroy the thread
sleep(MAX_INT);
}
}
And I have this in my main.
Test t = Test();
t.thread_foo("random stuff1");
t.thread_foo("random stuff2");
...
How can I parallelize these two calls without using a thread in my main so my main keeps going ? Where do I put my join() if I need one and how to destroy the first thread ?
I have been having a hard time with online tutorials as they always call std::thread in the main().

That's how you make a thread:
#include <thread>
int main() {
Test t = Test();
std::thread(t.thread_foo, "random stuff1").detach()
std::thread(t.thread_foo, "random stuff2").detach()
// Works in parallel
}

Related

How to run method/function on a separate thread in c++

I am a beginner to c++, so I don't know much
here is a function
void example(){
for(int i=0; i<5; i++){
// do stuff
}
}
if I call this function, it will wait for it to be finished before continuing
int main(){
example();
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
return 0;
}
the otherThingsGoHere() doesn't get called until example() is done
my goal is to have that function be able to loop 60/70 fps in a loop forever
and I did get it working, except nothing below that will happen since it is in an infinite loop.
I've been a c# developer for some time and I know that in c#, you can use async functions to run on a seperate thread. How do I impliment something like this in c++?
Edit: I am not asking for you to put the otherThingsGoHere in front of the main because the other things is going to be another loop, so I need both of them to run at the same time
You need to use a std::thread and run the example() function from that new thread.
A std::thread can be started when constructed with a function to run.
It will run potentially in parallel to the main thread running the otherThingsGoHere.
I wrote potentially because it depends on your system and number of cores. If you have a PC with multiple cores it can actually run like that.
Before main() exits it should wait for the other thread to end gracefully, by calling thread::join().
A minimal example for your case would be:
#include <thread>
#include <iostream>
void example() {
for (int i = 0; i<5; i++) {
std::cout << "thread...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void otherThingsGoHere() {
std::cout << "do other things ...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
int main() {
std::thread t{ example };
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
t.join();
return 0;
}
Some more info here: Simple example of threading in C++

c++ timer terminate without an active exception?

I want to design a timer in c++, to execute my function after a fixed time.
the code likes like:
#include <thread>
typedef void (*callback)();
class timer {
public:
void start(int sec, callback f) {
std::thread t([&sec, &f]() {sleep(sec); f();});
}
};
void test () {
printf("here called\n");
}
int main() {
timer t;
t.start(3, test);
while (1);
}
but when i run this code, i got:
terminate called without an active exception
[1] 3168208 abort (core dumped) ./a.out
can you help on this? and, any suggestions for a more flexible timer design?
You created a std::thread and destructed it without detaching it.
std::thread t([&sec, &f]() {sleep(sec);
Either call join to wait on it, or call detach.
Note also the capture by reference issue in your comments.
There are a few problems with your code that need to be addressed:
After spawning a std::thread you need to synchronize it using std::thread::join().
Remove the reference capture from the sec parameter in order to prevent dangling of references by the end of the scope of start().
sleep() is platform-dependent, so your code will only work for certain platforms that support it. Instead use, std::this_thread::sleep_for(std::chrono::seconds(sec));
#include <thread>
#include <chrono> // For std::chrono
#include <cstdio> // For printf
typedef void (*callback)();
class timer {
// Bring the thread object outside the function and make it an instance variable of the class
std::thread t;
public:
// Spawns a thread
void start(int const sec, callback&& f) {
if (t.joinable()) // If the object already has a thread attached to it, call 'join()' on it
t.join();
/* Capture 'sec' by value as it is a local variable, consequently, capture
'f' by reference as it is a function and its lifetime is throughout the whole
program */
t = std::thread([sec, &f]() {
std::this_thread::sleep_for(std::chrono::seconds(sec));
f();
});
}
// After the class gets destroyed, the thread is synchronized
~timer() {
t.join();
}
};
void test () {
printf("here called\n");
}
int main() {
timer t;
t.start(3, test);
}

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

std::thread::join blocks indefinitely out of main

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.

how to run a static function in a new thread?

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