How to run method/function on a separate thread in c++ - 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++

Related

C++ Multithreading methods in an object with infinite loops

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
}

run function in a interval while also running main code

Basically I am trying to run 2 pieces of code concurrently without freezing eachother, and one of the requires some delay.
so, initial code looks like this:
int main() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166)); // this freezes the whole program for 166 ms
// do other things
}
i have figured a way with threads:
void ThreadFunction() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
int main() {
std::thread t1(ThreadFunction);
t1.detach();
// do other things while also doing what the thread t1 does without waiting 166ms
}
This is not exactly my code, but i am trying to recreate code that works as an example.
Threads work fine, but i hear people saying thread.detach() is not good.
So what are the alternatives?
Your second example seems to be what you want. If you do not want to detach the thread, then don't do it. However, then you must join it and you can only join a thread when it finishes its work at some point.
For this simple example I suggest the following (otherwise you need a condition variable or similar to signal the thread that it should stop):
void ThreadFunction() {
for (int i=0; i <100; ++i) {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
}
int main() {
std::thread t1(ThreadFunction);
// do other things while also doing what the thread t1 does without waiting 166ms
t1.join(); // blocks until ThreadFunction returns
}
For C++20 you can also use std::jthread
The difference to std::thread is that it will auto join on destruction, thus the code reduces to:
int main() {
std::jthread t1(ThreadFunction);
// do other things while also doing what the thread t1 does without waiting 166ms
// t1.join() will be called automatically when the current scope exits
}

how to run some method that will run on different thread every 2 seconds?

I want to write some code that on the main it will start some thread that will run every 2 seconds and will print something on the console.
the start function need to be something like this
void StartTask(void* methodRoRun, long repeatTimeInSeconds);
that mean that the method receive pointer to function (methodRoRun) that will run every repeatTimeInSeconds seconds.
I can't find how to do it in C++
Something like this:
#include <thread>
#include <functional>
void f() {
printf("Task started\n");
// do stuff
}
void StartTask(std::function<void()> methodRoRun, long repeatTimeInSeconds) {
std::thread th([methodRoRun, repeatTimeInSeconds]() {
while (true ) {
methodRoRun();
std::this_thread::sleep_for(std::chrono::seconds(repeatTimeInSeconds));
}
});
th.detach();
}
int main() {
StartTask([](){ f(); }, 1);
while (true) {}
return 0;
}
Edit:
People are correctly pointing out this that detaching threads and having endless loops is not good practice, but the example just illustrates the approach.

C++11 std::threads and waiting for threads to finish

I have a vector of Timer Objects. Each Timer Object launches an std::thread that simulates a growing period. I am using a Command pattern.
What is happening is each Timer is getting executed one after another but what I really want is for one to be executed....then once finished, the next one...once finished the next...while not interfering with the main execution of the program
class Timer
{
public:
bool _bTimerStarted;
bool _bTimerCompleted;
int _timerDuration;
virtual ~Timer() { }
virtual void execute()=0;
virtual void runTimer()=0;
inline void setDuration(int _s) { _timerDuration = _s; };
inline int getDuration() { return _timerDuration; };
inline bool isTimerComplete() { return _bTimerCompleted; };
};
class GrowingTimer : public Timer
{
public:
void execute()
{
//std::cout << "Timer execute..." << std::endl;
_bTimerStarted = false;
_bTimerCompleted = false;
//std::thread t1(&GrowingTimer::runTimer, this); //Launch a thread
//t1.detach();
runTimer();
}
void runTimer()
{
//std::cout << "Timer runTimer..." << std::endl;
_bTimerStarted = true;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
_bTimerCompleted = true;
std::cout << "Growing Timer Finished..." << std::endl;
}
};
class Timers
{
std::vector<Timer*> _timers;
struct ExecuteTimer
{
void operator()(Timer* _timer) { _timer->execute(); }
};
public:
void add_timer(Timer& _timer) { _timers.push_back(&_timer); }
void execute()
{
//std::for_each(_timers.begin(), _timers.end(), ExecuteTimer());
for (int i=0; i < _timers.size(); i++)
{
Timer* _t = _timers.at(i);
_t->execute();
//while ( ! _t->isTimerComplete())
//{
//}
}
}
};
Executing the above like:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
start_timers();
}
void start_timers()
{
_timer.execute();
}
In Timers::execute I am trying a few different ways to execute the first and not execute the
next until I somehow signal it is done.
UPDATE:
I am now doing this to execute everything:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
//start_timers();
std::thread t1(&Broccoli::start_timers, this); //Launch a thread
t1.detach();
}
void start_timers()
{
_timer.execute();
}
The first time completes (I see the "completed" cout), but crashes at _t->execute(); inside the for loop with an EXEC_BAD_ACCESS. I added a cout to check the size of the vector and it is 2 so both timers are inside. I do see this in the console:
this Timers * 0xbfffd998
_timers std::__1::vector<Timer *, std::__1::allocator<Timer *> >
if I change the detach() to join() everything completes without the crash, but it blocks execution of my app until those timers finish.
Why are you using threads here? Timers::execute() calls execute on a timer, then waits for it to finish, then calls execute on the next, and so forth. Why don't you just call the timer function directly in Timers::execute() rather than spawning a thread and then waiting for it?
Threads allow you to write code that executes concurrently. What you want is serial execution, so threads are the wrong tool.
Update: In the updated code you run start_timers on a background thread, which is good. However, by detaching that thread you leave the thread running past the end of the scope. This means that the timer objects _g and _g1 and even the Timers object _timers are potentially destroyed before the thread has completed. Given the time-consuming nature of the timers thread, and the fact that you used detach rather than join in order to avoid your code blocking, this is certainly the cause of your problem.
If you run code on a thread then you need to ensure that all objects accessed by that thread have a long-enough lifetime that they are still valid when the thread accesses them. For detached threads this is especially hard to achieve, so detached threads are not recommended.
One option is to create an object containing _timers, _g and _g1 along side the thread t1, and have its destructor join with the thread. All you need to do then is to ensure that the object lives until the point that it is safe to wait for the timers to complete.
If you don't want to interfere with the execution of the program, you could do something like #Joel said but also adding a thread in the Timers class which would execute the threads in the vector.
You could include a unique_ptr to the thread in GrowingTimer instead of creating it as a local object in execute and calling detach. You can still create the thread in execute, but you would do it with a unique_ptr::reset call.
Then use join instead of isTimerComplete (add a join function to the Timer base class). The isTimerComplete polling mechanism will be extremely inefficient because it will basically use up that thread's entire time slice continually polling, whereas join will block until the other thread is complete.
An example of join:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void threadMain()
{
this_thread::sleep_for(chrono::seconds(5));
cout << "Done sleeping\n";
}
int main()
{
thread t(threadMain);
for (int i = 0; i < 10; ++i)
{
cout << i << "\n";
}
t.join();
cout << "Press Enter to exit\n";
cin.get();
return 0;
}
Note how the main thread keeps running while the other thread does its thing. Note that Anthony's answer is right in that it doesn't really seem like you need more than one background thread that just executes tasks sequentially rather than starting a thread and waiting for it to finish before starting a new one.

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.