I'm trying to create C++ program in the sense of embedded hardware programs that work in real time. The main loop in my C++ program uses a delay time of 250milliseconds. It's like:
int main()
{
do{
doSomething();
delay(250);
}while(1)
}
The delay in main loop is crucial for my program to operate.
I need to check something else using 5ms delays.
sideJob()
{
while(1){
checkSomething();
delay(5);
}
}
How do I define the function sideJob to run at the same with the main loop. All in all, I need to get the hang of threading by using, if possible, simple functions. I'm using Linux. Any help will be greately appreaciated.
EDIT: This is what I got so far, But I want to run the sideJob and main thread at the same time.
#include <string>
#include <iostream>
#include <thread>
using namespace std;
//The function we want to make the thread run.
void task1(string msg)
{
cout << "sideJob Running " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
//Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
while(1){
printf("Continuous Job\n");
}
}
Use different threads in order to do this tasks in parallel.
To learn for more about this, look here.
For an example on StackOverflow, look here.
You can also find plenty of tutorials out there (for example, here).
Related
I want to run some bunch of codes asynchronously in c++. This is for an gtk GUI application. I want to get the length from a encoder to an variable while running the other parts of the code. This lines of code should be always running. When i want the length, i should be able to get the current length from the variable. Can any one help me on this.
I haven't understood what exactly you want to do. But I think you can read more about the std::async.
#include <iostream>
#include <future>
void asyncFunction ()
{
std::cout << "I am inside async function\n";
}
int main()
{
std::future<void> fn = std::async(std::launch::async, asyncFunction);
// here some other main thread operations
return 0;
}
Function that is run asynchronously can also return a value, which can be accessed through the future with std::future::get blocking method.
I'm completely new to multithreading and have a little trouble understanding how multithreading actually works.
Let's consider the following example of code. The program simply takes file names as input and counts the number of lowercase letters in them.
#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <vector>
#include <string>
#include <fstream>
#include <ctype.h>
class LowercaseCounter{
public:
LowercaseCounter() :
total_count(0)
{}
void count_lowercase_letters(const std::string& filename)
{
int count = 0;
std::ifstream fin(filename);
char a;
while (fin >> a)
{
if (islower(a))
{
std::lock_guard<std::mutex> guard(m);
++total_count;
}
}
}
void print_num() const
{
std::lock_guard<std::mutex> guard(m);
std::cout << total_count << std::endl;
}
private:
int total_count;
mutable std::mutex m;
};
int main(){
std::vector<std::unique_ptr<std::thread>> threads;
LowercaseCounter counter;
std::string line;
while (std::cin >> line)
{
if (line == "exit")
break;
else if (line == "print")
counter.print_num(); //I think that this should print 0 every time it's called.
else
threads.emplace_back(new std::thread(&LowercaseCounter::count_lowercase_letters, counter, line));
}
for (auto& thread : threads)
thread->join();
}
Firstly I though that the output of counter.print_num() will print 0 as far as the threads are not 'joined' yet to execute the functions. However, It turns out that the program works correctly and the output of counter.print_num() is not 0. So I asked myself the following questions.
What actually happens when a thread is constructed?
If the program above works fine, then thread must be executed when is created, then what does std::thread::join method do?
If the thread is executed at the time of creation, then what's the point of using multithreading in this example?
Thanks in advance.
You seem to be under the impression that the program can only be running one thread at a time, and that it needs to interrupt whatever it's doing in order to execute the code of the thread. That's not the case.
You can think of a thread as a completely separate program that happens to share memory and resources with the program that created it. The function you pass as an argument is that program's 'main()` for every intent and purpose. In Linux, threads are literally separate processes, but as far as C++ is concerned, that's just an implementation detail.
So, in a modern operating system with preemptive multitasking, much like multiple programs can run at the same time, threads can also run at the same time. Note that I say can, it's up to the compiler and OS to decide when to give CPU time to each thread.
then what does std::thread::join method do?
It just waits until the thread is done.
So what would happen if I didn't call join() method for each one of threads
It would crash upon reaching the end of main() because attempting to exit the program without joining a non-detached thread is considered an error.
As you said, in c++ the thread is executed when it is created all std::thread::join does is wait for the thread to finish execution.
In your code all the threads will start executing simultaneously in the loop and then the main thread will wait for each thread to finish execution in the next loop.
I have a void function that has a while (true) loop inside of it, and both Sleep(); and std::this_thread::sleep_for(std::chrono::milliseconds()); do nothing. And yes, I am aware I'm sleeping by millisecond and not seconds, by multi-threading I mean I have done:
std::thread nThread(Void);
nThread.detach();
When I just call the method, this issue doesn't occur, and it sleeps just fine.
Essentially what I'm doing:
#include <stdio.h>
#include <thread>
void thisisVoid()
{
while (true)
{
printf("Print");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main()
{
std::thread nThread(thisisVoid);
nThread.detach();
}
It's not the sleep that's the problem. You haven't really asked a question, but I think what you're saying is that if you don't detach, you get a crash.
Here's why...
C++ doesn't like you to exit the program with dangling threads. You can either detach them or join them. There's a startup time with your new thread, and if you just exit main at the bottom, your first thread probably hasn't run yet. And it hasn't been allowed to clean up because you haven't joined against it or detached it.
So you have to do one or the other in main(). If you join against it you'll wait until it's done. If you detach it, you could exit before he's even executed.
Hello i'm newbie in C++ specially on STL,
I need to create a function with an infinite loop to calculate and process big data (such as Genetic Algorithm), but i also need keep Ui responsive and update it within (after each round) that infinite loop and start/stop operation manually.
something like this:
bool working = false;
void do_process()
{
while(working)
{
// do some stuff
}
}
void btnStart()
{
working = true;
do_process();
}
void btnEnd()
{
working = false;
}
would you please guide me to a proper solution without any 3rdparty lib, thanks.
and apologies for terrible English.
The code below should get you started. But be careful, implementing a multi-threading application is generally a hard problem also for experienced users. Lot of knowledge is required about memory access synchronization and deadlock analysis. Consider the example below is really essential. For instance, in btnStart and btnStop you should check if a thread is already running. Checking the global bool working may require synchronization. Similarly, checking for null pointer may require synchronization. Bottom line, it is way more complicate than it may seem.
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <memory>
bool working = false;
std::unique_ptr<std::thread> t;
void do_process()
{
while(working)
{
std::cout << "Hi. I am a secondary thread and I am running.\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void btnStart()
{
working = true;
t.reset(new std::thread(do_process)); // start the thread
}
void btnEnd()
{
working = false; // inform the thread of termination
t->join(); // wait for thread termination
t.reset(NULL);
}
int main()
{
std::cout << "Hi, I am the main thread.\n";
std::cout << "I'll now launch another thread and sleep for a while\n";
btnStart();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
btnEnd();
std::cout << "What happened while I was slepping?\n";
return 0;
}
I am fairly new also to c++ but i have something that might help.
when i want to run something like an update to my code or to run something external without cramming my original project with code, i like to use ShellExecute to run another c++ program or external program. To use ShellExecute you need #include<windows.h>
For example if i want to update my program, i use #include<fstream>, #include<windows.h>, and #include<string> to check for a value in a file called 'updatereq.txt' (i make it my self). And in my program i run ifstream to check in the file if there is a '1'. If the if statement detects '1' it does this:
void Update(string filename)
{
ShellExecute(NULL,"open",filename.c_str(),NULL,NULL,SW_SHOWNORMAL)
}
This will run with:
HWND set as NULL, Operation set as: "open", File set as string:filenameconstant, Parameters set as NULL, Directory set as NULL(will run in the Directory of originally launching, usually at the main file), and Mode set as SW_SHOWNORMAL which will run it infront of you normally. This is also SW_SHOWMINIMIZED and SW_SHOWMAXIMIZED
Hope this helps!
PS: Remember to mention the file / program name that you are going to run when calling this function
I'm trying to get a hold on pthreads. I see some people also have unexpected pthread behavior, but none of the questions seemed to be answered.
The following piece of code should create two threads, one which relies on the other. I read that each thread will create variables within their stack (can't be shared between threads) and using a global pointer is a way to have threads share a value. One thread should print it's current iteration, while another thread sleeps for 10 seconds. Ultimately one would expect 10 iterations. Using break points, it seems the script just dies at
while (*pointham != "cheese"){
It could also be I'm not properly utilizing code blocks debug functionality. Any pointers (har har har) would be helpful.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;
string hamburger = "null";
string * pointham = &hamburger;
void *wait(void *)
{
int i {0};
while (*pointham != "cheese"){
sleep (1);
i++;
cout << "Waiting on that cheese " << i;
}
pthread_exit(NULL);
}
void *cheese(void *)
{
cout << "Bout to sleep then get that cheese";
sleep (10);
*pointham = "cheese";
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_create(&threads[0], NULL, cheese, NULL);
pthread_create(&threads[1], NULL, wait, NULL);
return 0;
}
The problem is that you start your threads, then exit the process (thereby killing your threads). You have to wait for your threads to exit, preferably with the pthread_join function.
If you don't want to have to join all your threads, you can call pthread_exit() in the main thread instead of returning from main().
But note the BUGS section from the manpage:
Currently, there are limitations in the kernel implementation logic for
wait(2)ing on a stopped thread group with a dead thread group leader.
This can manifest in problems such as a locked terminal if a stop sig‐
nal is sent to a foreground process whose thread group leader has
already called pthread_exit().
According to this tutorial:
If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
So, you shouldn't end the main function with the statement return 0;. But you should use pthread_exit(NULL); instead.
If this doesn't work with you, you may need to learn about joining threads here.