Optimal infinite C++ while loop with interval - c++

I have a question about the correctness of my code.
I'm making a app which is run as a daemon, it do some code in interval, code looks:
#include <iostream>
#include <thread>
using namespace std;
int main() {
thread([=]() {
while (true) {
try {
cout << "log" << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
}
catch (...) {
cout << "Some errors here :/" << endl;
}
}
}).detach();
while (true);
}
I'm worried weather this code is optimal, because in top I can see, that this program uses about 80% of the CPU.
Can I correct something?
Is my code equivalent to this one:
https://stackoverflow.com/a/21058232/5334833?

It appears that while(true); is UB.
You might just get rid of thread BTW:
int main() {
while (true) {
try {
std::cout << "log" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}
catch (...) {
std::cout << "Some errors here :/" << std::endl;
}
}
}

while(true); will cause your main thread to continuously loop and use 100% of a single CPU.
Assuming you are on Linux you can just call pause() instead which will suspend your main thread until a signal arrives.
As you aren't actually using your main thread is there a reason you are spawning a new thread at all? Can you just do your work in the main thread?

Related

C++ call a function every x seconds

I am trying to run run() function every 5 seconds without stopping while() loop (parallelly). How can I do that ? Thanks in advance
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void run()
{
this_thread::sleep_for(chrono::milliseconds(5000));
cout << "good morning" << endl;
}
int main()
{
thread t1(run);
t1.detach();
while(1)
{
cout << "hello" << endl;
this_thread::sleep_for(chrono::milliseconds(500));
}
return 0;
}
In your main function, it is important to understand what each thread is doing.
The main thread creates a std::thread called t1
The main thread continues and detaches the thread
The main thread executes your while loop in which it:
prints hello
sleeps for 0.5 seconds
The main thread returns 0, your program is finished.
Any time from point 1, thread t1 sleeps for 5 seconds and then prints good morning. This happens only once! Also, as pointed out by #Fareanor, std::cout is not thread-safe, so accessing it with the main thread and thread t1 may result in a data race.
When the main thread reaches point 4 (it actually never does because your while loop is infinite), your thread t1 might have finished it's task or not. Imagine the potential problems that could occur. In most of the cases, you'll want to use std::thread::join().
To solve your problem, there are several alternatives. In the following, we will assume that the execution of the function run without the std::this_thread::sleep_for is insignificant compared to 5 seconds, as per the comment of #Landstalker. The execution time of run will then be 5 seconds plus some insignificant time.
As suggested in the comments, instead of executing the function run every 5 seconds, you could simply execute the body of run every 5 seconds by placing a while loop inside of that function:
void run()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "good morning" << std::endl;
}
}
int main()
{
std::thread t(run);
t.join();
return 0;
}
If, for some reason, you really need to execute the run function every 5 seconds as stated in your question, you could launch a wrapper function or lambda which contains the while loop:
void run()
{
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "good morning" << std::endl;
}
int main()
{
auto exec_run = [](){ while (true) run(); };
std::thread t(exec_run);
t.join();
return 0;
}
As a side note, it's better to avoid using namespace std.
Just call your run function in seperate thread function like below. Is this ok for you?
void ThreadFunction()
{
while(true) {
run();
this_thread::sleep_for(chrono::milliseconds(5000));
}
}
void run()
{
cout << "good morning" << endl;
}
int main()
{
thread t1(ThreadFunction);
t1.detach();
while(1)
{
cout << "hello" << endl;
this_thread::sleep_for(chrono::milliseconds(500));
}
return 0;
}

Should threads created inside main and threads created inside functions behave differently?

I'm new to programming/C++ and I'm experimenting with simple multithreading. I have tried the following codes:
Example 1
#include <iostream>
#include <thread>
void printFunc() {
while(1) {
std::cout << "threadOne Running..." << std::endl;
}
}
int main() {
std::thread threadOne(printFunc);
threadOne.detach();
while(1) {
std::cout << "main running..." << std::endl;
}
return 0;
}
Example 2
#include <iostream>
#include <thread>
void printFunc() {
while(1) {
std::cout << "threadOne running..." << std::endl;
}
}
void initThread() {
std::thread threadOne(printFunc);
threadOne.detach();
}
int main() {
initThread();
while(1) {
std::cout << "main running..." << std::endl;
}
return 0;
}
When I run example 1 using Visual Studio in debug & release mode, it prints "main running..." most of the time and prints "threadOne running..." once in a while. But when I run example 2, it prints both of them (jumps between two prints "equally").
Edit:
Execution of example 1
Execution of example 2
Possible reason for what you're seeing;
Because you did not specify which version of C++ you're using, I'll assume its C++11;
As per Is cout thread-safe
Concurrent access to a synchronized (§27.5.3.4) standard iostream object’s formatted and unformatted input (§27.7.2.1) and output (§27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (§1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]
Meaning that you still have to synchronize both cout streams.
One way of doing that would be to wrap cout in your own class and assign it a mutex.

pthread C++ in Centos no run

This is my code:
void* task1(void* unused)
{
try {
cout << "Run Thread" << endl;
}catch (const char* msg) {
cout << msg << endl;
}
}
int main(int argc, char *argv[])
{
try {
pthread_t thread_id;
int res = pthread_create(&thread_id, NULL, &task1, NULL);
cout << res << std::endl;
exit(EXIT_SUCCESS);
}catch (const char* msg) {
cout << msg << endl;
}
}
In Ubuntu Code RUN.
In CentOS Code NOT RUN, if my use pthread_join(thread_id, NULL); code is run but can waiting pthread complete. I try pthread_tryjoin_np but code not run.
Please help me run code in centos is no wating
If the program main() exits before the thread actually starts (and runs to the point cout << ...), the thread will be terminated and not continue to run.
I.e. you need to wait with pthread_join() before the main() exits.
The case in Ubuntu is a pure coincidence, that the thread manages to print the line before it is terminated by the C++ runtime after the main() exits.
If you do not want to wait because you want to start multiple threads, you can use thread pool (array of threads). First you start all of them, and then you pthread_join() wait for all of them to finish.
Also, if the pthread_join() blocks although the thread terminated, make sure you created the thread as joinable. That is the default, so make sure that you do not explicitly set the thread attributes to PTHREAD_CREATE_DETACHED.
To be absolutely sure, you can provide thread create attributes explicitly and ensure that the thread is created as joinable:
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread_id, &attr, &task1, NULL);
pthread_attr_destroy(&attr);
pthread_join(thread_id, NULL);
(error handling not included)
Why you do not use C ++ 11? Standard library (STL) have the opportunity to develop crossplatform applications with threads. You can test on cpp.sh
#include <iostream>
#include <thread>
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
}
int main()
{
std::thread thr(task1,1);
thr.join();
return 0;
}
OR
#include <iostream>
#include <thread>
#include <chrono>
bool bThread = false;
void task1(int used)
{
std::cout << "Run Thread " << used << std::endl;
bThread = true;
}
int main()
{
std::thread thr(task1,1);
try
{
thr.detach();
while (!bThread) std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
catch(...) { return 1; }
return 0;
}

How can I execute two threads asynchronously using boost?

I have the book "beyond the C++ standard library" and there are no examples of multithreading using boost. Would somebody be kind enough to show me a simple example where two threads are executed using boost- lets say asynchronously?
This is my minimal Boost threading example.
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction()
{
int counter = 0;
for(;;)
{
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main()
{
// Start thread
boost::thread t(&ThreadFunction);
// Wait for Enter
char ch;
cin.get(ch);
// Ask thread to stop
t.interrupt();
// Join - wait when thread actually exits
t.join();
cout << "main: thread ended" << endl;
return 0;
}

Bizarre thread printing behaviour

Hey - I'm having an odd problem with a little toy program I've written, to try out threads.
This is my code:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
void *threadFunc(void *arg) {
cout << "I am a thread. Hear me roar." << endl;
pthread_exit(NULL);
}
int main() {
cout << "Hello there." << endl;
int returnValue;
pthread_t myThread;
returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);
if (returnValue != 0) {
cout << "Couldn't create thread! Whoops." << endl;
return -1;
}
return 0;
}
With the first cout in main not commented out, the thread prints fine.
However, without it, the thread doesn't print anything at all.
Any help?
Try this:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
void *threadFunc(void *arg) {
cout << "I am a thread. Hear me roar." << endl;
pthread_exit(NULL);
}
int main() {
//cout << "Hello there." << endl;
int returnValue;
pthread_t myThread;
returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);
if (returnValue != 0) {
cout << "Couldn't create thread! Whoops." << endl;
return -1;
}
pthread_join( myThread, NULL);
return 0;
}
The difference between my code and yours is one line - pthread join. This suspends the main thread until the sub-thread has had chance to complete its actions.
In your code, execution reaches the first cout and it's processed. Then, you split off another thread and the main thread carries on until the end, which may or may not be reached before the secondary thread is tidied up. That's where the odd behaviour comes in - what you are experiencing is the case where the main program finishes before the sub-thread has had a chance to, so the program has "returned" and the whole lot is cleaned up by the kernel.
It's a race condition that allows the program to work when the main loop takes a little while to run. Your program is exiting before the thread even has a chance to run.
You should wait for the thread to complete (see pthread_join) before returning from main().
The fact that it works in one case is pure luck. You have a timing issue, which is your program is exiting before your thread does it's work.
When main() exits all your threads will die. You need some sort of waiting in place to give the other thread time to run before main() exits. Try adding a cin in main() after you create the worker thread and see what happens.
Ultimately you'll want some sort of run-loop and messaging/eventing to communicate between threads.
-jeff
Try adding a pthread_exit(NULL); at the end of main, before the return 0. I suspect that the problem is your main returns and the process exits before the thread has a chance to print. Printing from main might be somehow modifying the timing such that the thread does get a chance to print -- but that's is just sheer luck. You need to ensure that main doesn't return until all of your threads are finished doing their work. Calling pthread_exit from main allows other threads to continue running until they too have called pthread_exit.