how to execute a particular code in c++ after every 1 minute - c++

I need to make something(i call it a scheduler) that checks the time of the sytem every minute and if the time has changed suppose it is 17:52 and the next moment it is 17:53so at 17:53 it calls a function logupdated
How do i make this simply i m not known to the mutex and all.
Thanks

I am not sure I understand the requirements, but your question reads "how to execute a particular code in c++ after every 1 minute", so, in c++11 you can do this:
#include <thread>
#include <chrono>
int main() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(60));
// call your c++ code
}
}

If you want the execution of the task to be independent of the main program flow, consider multithreading.
this example in C, should work also on C++
Note that some people think that I use pointers excessively, I agree, specially with multithreading, it can cause unsafe threads, thus data corruption or even worse, segmentation faults.
However this is the only way to pass arguments to threads as far as I could find.
#include <pthread.h>
int main(int argc, char *argv[]) {
pthread_t thread1;
int variables=10;
pthread_create( &thread1, NULL, scheduler, (void*)&variables);
while(1){
.... do stuff as main program.
}
return 0;
}
void *scheduler (void* variables) {
int vars;
int* p_vars = (int*) variables;
vars = *p_vars;
while (1){
.. do scheduler stuff
sleep (vars);
}
}

Related

How to correctly handle SIGBUS so I can continue to search an address?

I'm currently working on a project running on a heavily modified version of Linux patched to be able to access a VMEbus. Most of the bus-handling is done, I have a VMEAccess class that uses mmap to write at a specific address of /dev/mem so a driver can pull that data and push it onto the bus.
When the program starts, it has no idea where the slave board it's looking for is located on the bus so it must find it by poking around: it tries to read every address one by one, if a device is connected there the read method returns some data but if there isn't anything connected a SIGBUS signal will be sent to the program.
I tried several solutions (mostly using signal handling) but after some time, I decided on using jumps. The first longjmp() call works fine but the second call to VMEAccess::readWord() gives me a Bus Error even though my handler should prevent the program from crashing.
Here's my code:
#include <iostream>
#include <string>
#include <sstream>
#include <csignal>
#include <cstdlib>
#include <csignal>
#include <csetjmp>
#include "types.h"
#include "VME_access.h"
VMEAccess *busVME;
int main(int argc, char const *argv[]);
void catch_sigbus (int sig);
void exit_function(int sig);
volatile BOOL bus_error;
volatile UDWORD offset;
jmp_buf env;
int main(int argc, char const *argv[])
{
sigemptyset(&sigBusHandler.sa_mask);
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = exit_function;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
/* */
struct sigaction sigBusHandler;
sigBusHandler.sa_handler = catch_sigbus;
sigemptyset(&sigBusHandler.sa_mask);
sigBusHandler.sa_flags = 0;
sigaction(SIGBUS, &sigBusHandler, NULL);
busVME = new VMEAccess(VME_SHORT);
offset = 0x01FE;
setjmp(env);
printf("%d\n", sigismember(&sigBusHandler.sa_mask, SIGBUS));
busVME->readWord(offset);
sleep(1);
printf("%#08x\n", offset+0xC1000000);
return 0;
}
void catch_sigbus (int sig)
{
offset++;
printf("%#08x\n", offset);
longjmp(env, 1);
}
void exit_function(int sig)
{
delete busVME;
exit(0);
}
As mentioned in the comments, using longjmp in a signal handler is a bad idea. After doing the jump out of a signal handler your program is effectively still in the signal handler. So calling non-async-signal-safe functions leads to undefined behavior for example. Using siglongjmp won't really help here, quoting man signal-safety:
If a signal handler interrupts the execution of an unsafe function, and the handler terminates via a call to longjmp(3) or siglongjmp(3) and the program subsequently calls an unsafe function, then the behavior of the program is undefined.
And just for example, this (siglongjmp) did cause some problems in libcurl code in the past, see here: error: longjmp causes uninitialized stack frame
I'd suggest to use a regular loop and modify the exit condition in the signal handler (you modify the offset there anyway) instead. Something like the following (pseudo-code):
int had_sigbus = 0;
int main(int argc, char const *argv[])
{
...
for (offset = 0x01FE; offset is sane; ++offset) {
had_sigbus = 0;
probe(offset);
if (!had_sigbus) {
// found
break;
}
}
...
}
void catch_sigbus(int)
{
had_sigbus = 1;
}
This way it's immediately obvious that there is a loop, and the whole logic is much easier to follow. And there are no jumps, so it should work for more than one probe :) But obviously probe() must handle the failed call (the one interrupted with SIGBUS) internally too - and probably return an error. If it does return an error using the had_sigbus function might be not necessary at all.

Running a periodic loop in background in C++/C

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

Thread ending unexpectedly. c++

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.

Synchronise two threads passing events between each other

I am new to windows c++ programming. Please see the below code where I want to make the two threads synchronized. The first thread should print "Hello" then pass the control/event to the second thread. Not sure how to do it. As of now I am using Sleep(1000). But if I dont use Sleep it result into undefined behavior. Please help...
#include <windows.h>
#include <process.h>
#include <iostream>
void thread1(void*);
void thread2(void*);
int main(int argc, char **argv) {
_beginthread(&thread1,0,(void*)0);
_beginthread(&thread2,0,(void*)0);
Sleep(1000);
}
void thread1(void*)
{
std::cout<<"Hello "<<std::endl;
}
void thread2(void*)
{
std::cout<<"World"<<std::endl;
}
The problem is the question you are asking really doesn't make sense. Multiple threads are designed to run at the same time and you're trying to play a game of pass the buck from one thread to another to get sequential serialised behavoir. Its like taking a really complicated tool and ask how it solves what is normally a really easy question.
However, multithreading is a really important topic to learn so I'll try to answer what you need to the best of my ability.
Firstly, I'd recommend using the new, standard C++11 functions and libraries. For windows, you can download Visual Studio 2012 Express Edition to play about with.
With this you can use std::thread, std::mutex and a lot [but not all] of the other C++11 goodies (like std::condition_variable).
To solve your problem you really need a condition variable. This lets you signal to another thread that something is ready for them:
#include <iostream>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>
static std::atomic<bool> ready;
static std::mutex lock;
static std::condition_variable cv;
// ThreadOne immediately prints Hello then 'notifies' the condition variable
void ThreadOne()
{
std::cout << "Hello ";
ready = true;
cv.notify_one();
}
// ThreadTwo waits for someone to 'notify' the condition variable then prints 'World'
// Note: The 'cv.wait' must be in a loop as spurious wake-ups for condition_variables are allowed
void ThreadTwo()
{
while(true)
{
std::unique_lock<std::mutex> stackLock(lock);
cv.wait(stackLock);
if(ready) break;
}
std::cout << "World!" << std::endl;
}
// Main just kicks off two 'std::thread's. We must wait for both those threads
// to finish before we can return from main. 'join' does this - its the std
// equivalent of calling 'WaitForSingleObject' on the thread handle. its necessary
// to call join as the standard says so - but the underlying reason is that
// when main returns global destructors will start running. If your thread is also
// running at this critical time then it will possibly access global objects which
// are destructing or have destructed which is *bad*
int main(int argc, char **argv)
{
std::thread t1([](){ThreadOne();});
std::thread t2([](){ThreadTwo();});
t1.join();
t2.join();
}
Here is the simplified version to handle your situation.
You are creating 2 threads to call 2 different function.
Ideally thread synchronization is used to serialize same code between threads but in your case it is not the need. You are trying to serialize 2 threads which are no way related to one another.
Any how you can wait for each thread to finish by not making async call.
#include <windows.h>
#include <process.h>
#include <iostream>
#include<mutex>
using namespace std;
void thread1(void*);
void thread2(void*);
int main(int argc, char **argv) {
HANDLE h1 = (HANDLE)_beginthread(&thread1,0,(void*)0);
WaitForSingleObject(h1,INFINITE);
HANDLE h2 = (HANDLE)_beginthread(&thread2,0,(void*)0);
WaitForSingleObject(h2,INFINITE);
}
void thread1(void*)
{
std::cout<<"Hello "<<std::endl;
}
void thread2(void*)
{
std::cout<<"World"<<std::endl;
}
You can group both beginthread in single function and call that function in while loop if you want to print multiple times.
void fun()
{
HANDLE h1 = (HANDLE)_beginthread(&thread1,0,(void*)0);
WaitForSingleObject(h1,INFINITE);
HANDLE h2 = (HANDLE)_beginthread(&thread2,0,(void*)0);
WaitForSingleObject(h2,INFINITE);
}

(simple) boost thread_group question

I'm trying to write a fairly simple threaded application, but am new to boost's thread library. A simple test program I'm working on is:
#include <iostream>
#include <boost/thread.hpp>
int result = 0;
boost::mutex result_mutex;
boost::thread_group g;
void threaded_function(int i)
{
for(; i < 100000; ++i) {}
{
boost::mutex::scoped_lock lock(result_mutex);
result += i;
}
}
int main(int argc, char* argv[])
{
using namespace std;
// launch three threads
boost::thread t1(threaded_function, 10);
boost::thread t2(threaded_function, 10);
boost::thread t3(threaded_function, 10);
g.add_thread(&t1);
g.add_thread(&t2);
g.add_thread(&t3);
// wait for them
g.join_all();
cout << result << endl;
return 0;
}
However, when I compile and run this program I get an output of
$ ./test
300000
test: pthread_mutex_lock.c:87: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
Aborted
Obviously, the result is correct but I'm worried about this error message, especially because the real program, which has essentially the same structure, is getting stuck at the join_all() point. Can someone explain to me what is happening? Is there a better way to do this, i.e. launch a number of threads, store them in a external container, and then wait for them all to complete before continuing the program?
Thanks for your help.
I think you problem is caused by the thread_group destructor which is called when your program exits. Thread group wants to take responsibility of destructing your thread objects. See also in the boost::thread_group documentation.
You are creating your thread objects on the stack as local variables in the scope of your main function. Thus, they have already been destructed when the program exits and thread_group tries to delete them.
As a solution, create your thread objects on the heap with new and let the thread_group take care of their destruction:
boost::thread *t1 = new boost::thread(threaded_function, 10);
...
g.add_thread(t1);
...
If you don't need a handle to your threads, try using thread_group::create_thread() which alleviates the need to manage the thread at all:
// Snip: Same as previous examples
int main(int argc, char* argv[])
{
using namespace std;
// launch three threads
for ( int i = 0; i < 3; ++i )
g.create_thread( boost::bind( threaded_function, 10 ) );
// wait for them
g.join_all();
cout << result << endl;
return 0;
}
add_thread() takes ownership of thread you pass in. Thread group deletes the thread. In this example you are deleting memory allocated on stack, pretty much a capital offence.
Member function add_thread()
void add_thread(thread* thrd);
Precondition:
The expression delete thrd is
well-formed and will not result in
undefined behaviour.
Effects:
Take ownership of the boost::thread
object pointed to by thrd and add it
to the group.
Postcondition:
this->size() is increased by one.
Not sure if that's what's wrong in your code, or if this is just example bug. Otherwise code looks fine.
It looks none of above actually answered the question.
I met the similar issue. The consequence of this warning (pthread_mutex_lock.c:87: __pthread_mutex_lock: Assertion `mutex->_data._owner == 0' failed.
Aborted) is that sometimes the program will leak threads and cause a boost_resource_error exception.
The reason looks like the program continues to execute after join_all() although most of threads are still running ( not terminated ).