Why isn't setjmp saving the stack? - c++

Why isn't setjmp saving the stack?
Consider the following code:
#include <iostream>
jmp_buf Buf;
jmp_buf Buf2;
void MyFunction()
{
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
if(!setjmp(Buf))
longjmp(Buf2, 1);
}
}
int main (int argc, const char * argv[])
{
while(true)
{
if(!setjmp(Buf2))
{
MyFunction();
break;
}
longjmp(Buf, 1);
}
return 0;
}
What I except is that the code will jump back and forth from main to the function and back printing increasing number every time.
What actually happens is that it prints 0 and then 1 infinite number of times. it is as if when it jumps back into the function the stack is reset to defaults. why is it doing it? is there any way I can make it save the stack too?
I know setjmp and longjmp are even worse than goto when it comes to coding style and readable code, but I am experimenting right now, and this code will probably never see the light of a usable application.

Because unfortunately thats not how setjmp works. setjmp copies the current instruction pointer and register set into the jump buffer but it does not copy the stack (obviously be cause the stack is huge). It looks like you want to use some kind of coroutine based techniques. If you want to do this yourself checkout the ucontext procedured (ucontext.h) http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?ucontext.h+3 they will help you to allocate and manage additionaly thread stacks.
or you could use something like Russ Cox's libtask (http://swtch.com/libtask/) which will help do this for you. Or if you want to do it yourself you should take a look at the libtask code (also available through that link). It's pretty easy to read so its a good resource.

Related

C/C++ thread calling filling up memory

I am trying to make a server(multithreading) and I run into a problem: it is filling up memory. So I decided to do a simple test. Here is the code in main:
int main(void)
{
int x;
while(1)
{
cin>>x;
uintptr_t thread = 0;
//handle(NULL);
thread = _beginthread(handle, 0, NULL);
if (thread == -1) {
fprintf(stderr, "Couldn't create thread: %d\n", GetLastError());
}
}
}
And here is the 'handle' function:
void handle(void *)
{
;
}
I open task manager, and I am looking there to see how much RAM my process takes.
If the function main is as you see right now, after each press of key 1 and then press enter(so the thing inside the while will execute), the RAM that the process takes increases with 4k(basically, each time the thread is created or something like that, it will leak 4k of memory). If I do this multiple times, it will keep increasing, each time with 4k.
If in the function main I comment this 'thread = _beginthread(handle, 0, 0);' and uncomment this '//handle(NULL);', then the process will not increase it's RAM memory.
Anyone have any ideas how to free that 4k of memory?
I am compiling it with codeblocks, but same result is compiling it with visual studio.
EDIT: from MSDN: "When the thread returns from that routine, it is terminated automatically."
Also I put '_endthread();' in my handle function, but the result IS THE SAME!
Each time around the loop this program creates a new thread. The program never closes any threads.
I think what you have demonstrated is that the memory cost of creating a thread is around 4K.
Presuming you don't want an ever-increasing number of threads, either you should close one before creating another or at least give up when you've got enough.
On further reflection, the above is wrong. I tried your program, and it will not and cannot do what you say, unless there is some important part of the story you've left out.
The line with "cin" just blocks. I pressed enter a few times, but nothing interesting happened. So I took it out.
This program does not leak. Each thread terminates when the handle function finishes.
Here is the code I wrote, adapting yours.
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
int nthread = 0;
void handle(void *) {
nthread++;
}
int main(int argc, char* argv[]) {
while(nthread < 50000) {
cout << nthread << ' ';
uintptr_t thread = 0;
thread = _beginthread(handle, 0, NULL);
if (thread == -1) {
fprintf(stderr, "Couldn't create thread: %d\n", GetLastError());
break;
}
}
}
It runs 50,000 iterations and uses a grand total of less than 1MB of memory. Exactly as expected.
Something doesn't add up.
Every thread need some memory for it's own infrastructure, that's what the 4K is. When the thread terminates (this depends on your implementation), this 4K will be freed. You should use API functions for joining the the child threads, therefore you should keep the handle(s). Calling the handle function directly is just a function call, no memory is allocated in this case.
EDIT:
Your "handle" function terminates immediately. As far as I know (at least for posix/linux) there are options at creation time for auto-free the memory, or otherwise joining is required. The one thread you see is the "main" thread of the process itself. This way your programm is producing memory leaks.

C++ While loop, usleep()/sleep() how not to use 90% of CPU? (Ubuntu 12.04)

Suppose I have C++ code such as
#include "myheaderfiles.h"
//..some stuff
//...some more stuff
int main()
{
double milliseconds;
int seconds;
int minutes;
int timelimit=2;
...
...
//...code here that increments
//.....milliseconds,seconds, and minutes
while(minutes <=timelimit)
{
//...do stuff
if(milliseconds>500)
{
//...do stuff
//...every half second
} //end if
} //end while
}//end main
The program will run fine and does what its supposed to do but it will use up 90%+ of my cpu.
It was suggested to me to use usleep() in my while loop ever 100ms or so since I really only care about doing stuff every 500ms anyway. That way, it hog the CPU when its not needed.
So I added it to my while loop like so
while(minutes <=timelimit)
{
//...do stuff
if(milliseconds>500)
{
//...do stuff
//...every half second
} //end if
usleep(100000);
} //end while
It compiles fine, but when I run it, the program will hang right at usleep and never return. I read somewhere that before calling usleep, one needs to flush all buffers, so I flushed all file streams and couts etc etc. Still no luck.
I've searched for 2 days for a solution. I've used sleep() too, with no luck.
I found a few alternatives but they seem complicated and will add a lot of code to my program that I dont really fully understand which will complicate it and make it messy, plus it might not work.
I never really put too much thought in my while() loops before because most of the programs I wrote were for microcontrollers or FPGAs which is no problem to hog the processor.
If anyone can help.... any resources, links,books? Thanks.
Your approach somewhat comes from the wrong end. A program should consume 90-100% CPU as long as it has something useful to do (and it should block otherwise, consuming zero CPU).
Sleeping in between will cause execution being longer for no good reason, and consume more energy than just doing the work as fast as possible (at 100% CPU) and then completely blocking until more work is available or until some other significant thing (e.g. half a second has passed, if that matters for you) happens.
With that in mind, structure your program in a way conceptually like:
while(blocking_call() != exit_condition)
{
while(have_work)
do_work();
}
Also, do not sleep during execution, but use timers (e.g. setitimer) to do something at regular intervals. Not only will this be more efficient, but also a lot more precise and reliable.
How exactly you implement this depends on how portable you want your software to be. Under Ubuntu/Linux, you can for example use APIs such as epoll_wait with eventfd rather than writing a signal handler for the timer.
This code works as expected for me (running on OSX though).
#include <unistd.h>
#include <iostream>
int main() {
std::cout << "hello" << std::endl;
int i = 0;
while(i < 10) {
++i;
usleep(100000);
std::cout << "i = " << i << std::endl;
}
std::cout << "bye" << std::endl;
return 0;
}
There is a logical issue or maybe you're making multiple counters? Since you said you've done microcontrollers, I assume you're trying to use clock-cycles as a method of counting while calling the system timers? Also, what has me questioning is if you're recommended to use usleep(x), why are you using double for millisecond? usleep(1) is 1 microsecond == 1000 milliseconds. The sleep(x) is a counter per x second, so the system will suspend it's current task for x amount of seconds.
#include <iostream>
#include <unistd.h>
using namespace std;
#define MILLISECOND 1000
#define SECOND 1000*MILLISECOND
int main(int argc, char *argv[]){
int time = 20;
int sec_counter = 0;
do{
cout<<sec_counter<<" second"<<endl;
usleep(SECOND);
sec_counter++;
} while(sec_counter<time+1);
return 0;
}
If you wanted to use 500ms then replace usleep(SECOND) with usleep(500*MILLISECOND).
I suggest you use a debugger and step through your code to see what's happening.

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

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

Passing new data to an asynchronous, threaded function that may still be using the old data

I am having some problem related to C/C++:
Suppose I have some class
class Demo
{
int constant;
public:
void setConstant(int value)
{
constant=value;
}
void submitTask()
{
// need to make a call to C-based runtime system to submit a
// task which will be executed "asynchronously"
submitTask((void *)&constant);
}
};
// runtime system will call this method when task will be executed
void func(void *arg)
{
int constant= *((int *)arg);
// Read this constant value but don't modify here....
}
Now in my application, I do something like this:
int main()
{
...
Demo objDemo;
for(...)
{
objDemo.setConstant(<somevalue>);
objDemo.submitTask();
}
...
}
Now, hopefully you see the problem as tasks should read the value set immediately before a asynchronous call . As task calls are asynchronous so a task can read wrong value and sometimes results in unexpected behavior.
I don't want to enforce synchronous task execution just because of this constraint. The number of tasks created are not known in advance. I just need to pass this simple integer constant in an elegant way that will work with asynchronous. Obviously I cannot change the runtime behavior (mean that signature of this method void func(void *arg) is fixed).
Thanks in advance.
If you don't want to wait for the C code to finish before you make the next call then you can't reuse the same memory location over and over. Instead, create an array and then pass those locations. For this code, I'm going to assume that the number of times the for loop will run is n. This doesn't have to be known until it's time for the for loop to run.
int* values = new int[n];
for(int i=0;i<n;i++) {
values[i] = <somevalue>;
submitTask((void*)&values[i]);
}
At some later point when you're sure it's all done, then call
delete[] values;
Or, alternately, instead of an array of ints, create an array of Demo objects.
Demo demo[] = new Demo[n];
for(int i=0;i<n;i++) {
demo[i].setConstant(<somevalue>);
demo[i].submitTask();
}
But the first makes more sense to me as the Demo object doesn't really seem to do anything worthwhile. But you may have left out methods and members not relevant to the question, so that could change which option is best. Regardless, the point is that you need separate memory locations for separate values if you don't know when they're going to get used and don't want to wait.

Simple use of Leaks Instrument on a console application

I would like a simple example on how to use the Leaks tool.
see:
#include <iostream>
int main (int argc, char * const argv[]) {
char *buf = new char[100];
sprintf(buf, "Hello, World!\n");
// insert code here...
std::cout << buf;
return 0;
}
the code above(simple example) should leak the pointer allocated on *buf, right?
with valgrind I would find this very easy after a run
but I just can't find how to do this on the Leaks program
I tried to put sleep(60) but it is still not friendly to me...
thanks,
Jonathan
I've found that Leaks doesn't work all that well with command line applications that exit quickly. I would suggest adding a sleep() like you've done, but add one before the main program logic, and again at the end, so that Leaks is likely to sample the leaked state.
int main() {
sleep(20); // 20s may be enough
{
// do leaky operations, then local variables will go out of scope
}
sleep(20);
}