How can I watch multiple variables while debugging without stopping at breakpoints? - c++

Suppose I have a complex C++ application that I need to debug with a lot of variables. I wanna avoid using std::cout and printf approaches (below there's an explaination why).
In order to explain my issue, I wrote a minimal example using chrono (This program calculates fps of its while cycle over time and increment i_times counter until it reaches 10k):
#include <chrono>
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv){
bool is_running = true;
float fps;
int i_times=0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
while(is_running){
start = chrono_hclock::now();
// Some code execution
end = chrono_hclock::now();
fps=(float)1e9/(float)std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count());
if(++i_times==10000) is_running=false;
}
return 0;
}
I would like to debug this program and watch for fps and i_times variables continuosly over time, without stopping execution.
Of course I can simply use std::cout, printf or other means to output variables values redirecting them to stdout or a file while debugging and those are OK for simple types, but I have multiple variables which data type are struct-based and it would be creepy, time expensive and code bloating to write instructions to print each one of them. Also my application is a realtime video/audio H.264 encoder streaming with RTSP protocol and stopping at breakpoints means visualizing artifacts in my other decoder application because the encoder can't keep up with the decoder (because the encoder hit a breakpoint).
How can I solve this issue?
Thanks and regards!
The IDE I'm currently using for developing is Visual Studio 2019 Community.
I'm using the Local Windows Debugger.
I'm open to using alternative open source IDEs like VSCode or alternative debugging methods to solve this problem and/or to not be confinated into using a specific IDE.
To watch for specific multiple variables in VS I use the built-in Watch Window. While debugging with LWD, I add manually variables by right-clicking them in my source code and click Add Watch. Then those are showed in the Watch Window (Debug-Windows-Watch-Watch 1):
However I can only watch this window contents once I hit a breakpoint I set inside the while cycle, thus blocking execution, so that doesn't solve my issue.

You can use nonblocking breakpoint. First add the breakpoint. Then click on breakpoint settings or right click and select action.
Now you add a message like any string that is suggestive for you. And in brackets include the values to show, for instance
value of y is {y} and value of x is {x}
In the image is shown the value of i when it hits the breakpoint. Check the "Continue code execution" so breakpoint will not block execution. The shape of your breakpoint will change to red diagonal square. You can add also specific conditions if you click the Conditions checkbox.
Now while debugging all these debug messages will be shown in the output window:
In the above image it is showing the following message:
the value of i is {i}
By checking the "Conditions" you can add specific conditions, for instance i%100==0 and it will show the message only if i is divisible by 100.
This time your breakpoint will be marked with a + sign, meaning it has condition. Now while debugging there will be shown the i only when divisible by 100, so you can restrict the output to some more meaningful cases

The strict answer is "no" but...
I think I understand what you're trying to accomplish. This could be done by dumping the watched variables into to shared memory which is read by 2nd process. A watch and a break point in the 2nd would allow you to see the values in Visual Studio without interrupting the original application.
A few caveats:
UAC must be admin on both sides to open the memory handle
This wouldn't work with pointers as the 2nd program only has access to the shared memory
Windows anti-virus went nuts for the first few times I
ran this but eventually calmed down
Worker application:
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <windows.h>
#include <chrono>
#include <thread>
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv)
{
bool is_running = true;
float fps;
int i_times = 0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
HANDLE map_file;
void* shared_buffer;
// Set up the shared memory space
map_file = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(watch_collection), SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Didn't work, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file); // Didn't work, clean up the file handle and bail.
return 1;
}
// Do some stuff
while (is_running) {
start = chrono_hclock::now();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
for (int k = 0; k < 10000; k++) {
watch_collection watches { i = i, j = j, k = k };
CopyMemory(shared_buffer, (void*)&watches, (sizeof(watch_collection))); // Copy the watches to the shared memory space
// Do more things...
}
}
}
end = chrono_hclock::now();
fps = (float)1e9 / (float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
if (++i_times == 1000000) is_running = false;
}
// Clean up the shared memory buffer and handle
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
Watcher application:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
int main()
{
HANDLE map_file;
void* shared_buffer;
bool is_running = true;
watch_collection watches; // Put a watch on watches
// Connect to the shared memory
map_file = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Couldn't open the handle, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file);
return 1;
}
// Loop forever
while (is_running)
{
CopyMemory((void*)&watches, shared_buffer, (sizeof(watch_collection)));
} // Breakpoint here
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}

Related

if there is a limit imposed by the standard library for threads count used by subprocess opened by system() command ? c++

I use thread lib to create multiple thread for my c++ program, and I call a executable program in each thread by using system() command. The executable program is multithreading itself.
so I want to ask if there is a limit for threads counts for the executable program called by system() could used in each thread , If there are some rule in thread library or standard library to limit the usage of thread for sub excutable program called by system()command?
Above is my question, If you have any question , you could read my code example below.
please ignore the progress_bar.h, it is nothing to do with my question, it's a head file which is used to show progress bar.
parallel.h is like:
#ifndef parallel_h
#define parallel_h
#include <vector>
#include <functional>
#include <atomic>
#include <thread>
#include "progress_bar.h"
//simple thread pool implementation
//updateFun should be thread-safe!
template <class T>
void processInParallel(const std::vector<T>& scheduledTasks,
std::function<void(const T&)> updateFun,
size_t maxThreads, bool progressBar)
{
if (scheduledTasks.empty()) return;
std::atomic<size_t> jobId(0);
ProgressPercent progress(scheduledTasks.size());
if (progressBar) progress.advance(0);
auto threadWorker = [&jobId, &scheduledTasks, &updateFun,
&progress, progressBar]()
{
while (true)
{
size_t expected = 0;
while(true)
{
expected = jobId;
if (jobId == scheduledTasks.size())
{
return;
}
if (jobId.compare_exchange_weak(expected, expected + 1))
{
break;
}
}
updateFun(scheduledTasks[expected]);
if (progressBar) progress.advance();
}
};
std::vector<std::thread> threads(std::min(maxThreads,
scheduledTasks.size()));
for (size_t i = 0; i < threads.size(); ++i)
{
threads[i] = std::thread(threadWorker);
}
for (size_t i = 0; i < threads.size(); ++i)
{
threads[i].join();
}
}
#endif /* parallel_h */
in main.cpp
#include "parallel.h"
#include <iostream>
#include <function>
#include <vector>
int main(int argc, char** argv){
std::vector<int> jobids = {1,2,3,4,5};
std::function<void(const int& jobid)>testfunc = [](const int& jobid)
{
system("Call another executable program here!");
};
size_t threadnum = 5;
processInParallel(testfunc, jobids, threadnum, true);
}
can anyone give me an answer?
There are two main limits for number of threads in Linux.
One is a limit for total amount of threads in system that can be checked in:
/proc/sys/kernel/threads-max. This limit is system-wide and it gives you insight how many threads can be run by kernel.
It's worth to look also on /proc/sys/vm/max_map_count as it contains information about how many virtual memory areas a process can own.
The second one is indirect limit connected with amount of virtual memory:
number of threads = total virtual memory / (stack size*1024*1024)
As you can create new threads with custom value of stack size this limit can vary. Increasing process virtual memory or decreasing stack size for new threads can allow you to run more threads within single process. Check ulimit for more information.
If your distribution is systemd-based you'd like to look also on UserTasksMax setting.

Cannot edit an std::atomic value in Visual Studio debugger

This is my test program:
#include <iostream>
#include <atomic>
std::atomic<int> Counter = 200;
int main()
{
if(Counter > 0)
std::cout << "Hello World!\n";
}
I'm setting a breakpoint to the if(Counter > 0), and when it is hit I'm adding Counter to the watch window:
As you can see, the "Edit Value" entry is greyed out and it's impossible to change the value in the debugger. Replacing the variable definition with int Counter = 200; makes it editable in the debugger, but I lose the associated memory ordering semantics which I need.
Is there a way to create a counter with at least a release-consume ordering which I would be able to manipulate via the debugger?
Yes add the following to your watch window: Counter._Storage._Value

C++ using proccesing power/time while console loading bar

I'm currently new to programming and don't know, how to let the program process while the loading bar is running.
I wanted to display the loading bar and check, wether the program is finished processing. If not, then the processing bar should simply begin to fill again.
My code now is just showing the loading bar once and begins to process after that. This is pretty useless.
I researched on Google and here on stack overflow, but i only got the loading bar from that, not the useful integration in my program.
I just need a simple way to check, wether there would be an output besides the loading bar and i need to run the rest of the program at the same time as the loading bar, just to save time.
#include <iostream>
#include <windows.h>
#include <unistd.h>
#include <string>
#include <thread>
using namespace std;
static void loading(){
system("Color 0A");
cout<<"\t\n\n";
char a=177, b=219;
cout<<"\t";
for (int i=0;i<=50;i++)
cout<<a;
cout<<"\r";
cout<<"\t";
for (int i=0;i<=50;i++){
cout<<b;
for (int j=0;j<=2e7;j++);
}
cout << "\n\n";
}
int main(){
//ProjectEuler Problem___
loading();
int j=0;
do{
j++;
}while(j<=1e9); //just an example to see when it is processing
cout << "hi" << endl;
return 0;
}
I'm grateful for any help.
The typical pattern you're looking for would look something like:
void do_expensive_work(std::atomic<bool>& done) {
... something expensive goes here...
done = true;
}
int main() {
std::atomic<bool> done = false;
auto t = std::thread(do_expensive_work, std::ref(done));
while (!done) {
... update your progress bar ...
... sleep a bit ...
}
t.join();
return 0;
}
The specifics of how you communicate the result of your computation back to the calling thread etc are up to you. Similarly, you could in theory use a global atomic for the done status, or wrap up the computation in a class that keeps track of state and manages the execution of the thread. Code above is greatly simplified but gives a general pattern.

Window Hangs And Freezes [SDL 2]

I have a text file full of information on where to place tiles in a game i'm making, the fastest way to access this information is with a for loop. But whenever i use the for loop to get through all the information it freezes the program for about 12 seconds, in those 12 i cant move the window, nothing on the renderer updates/is drawn, and then when i click on the window it breaks and says "window name (Not Responding)". I tried using a while loop but it still does the same thing.
How can i loop through bigger numbers (there are about 4,000 tiles in the level) without the program freezing/hanging on me? I'm just using SDL 2, no OpenGL involved.
int tiles = 4000;
int x[4000];
int y[4000];
tile obj[4000];
for(int i = 0; i < tiles; i++)
{
x[i] = txt.x;
y[i] = txt.y;
obj[i].Load(x[i], y[i]);
obj[i].Add();
SDL_RenderClear(ren);
LoadScreen();
SDL_RenderPresent(ren);
}
Thanks.
You need to create another thread.
It's good idea to wait for all data to load before starting game, so during load, you don't need to render anything. Even with this approach, it is better to use another thread and don't keep "UI Thread" busy. During load time your UI would be mostly disabled except a cancel button that will stop loading thread.
#include <process.h>
bool bReady;
void LoadTiles(void* pArg)
{
// Load Data here
*((int*)pArg) = 0;
///////////////////
bReady = true;
}
void main()
{
btnStart.SetEnabled(false);
bReady = false;
int iTarget;
uintptr_t hLoadingThread = _beginthread(LoadTiles, 0, &iTarget);
while (true) // usually you pick a message here
{
if (bReady)
btnStart.SetEnabled(true);
}
}
This is just a very simple example, multi-threading needs a lot of work and study!

Making a Timer in c++?

I am developing a simple game in c++, a chase-the-dot style one, where you must click a drawn circle on the display and then it jumps to another random location with every click, but I want to make the game end after 60 seconds or so, write the score to a text file and then upon launching the program read from the text file and store the information into an array and somehow rearrange it to create a high score table.
I think I can figure out the high score and mouse clicking in a certain area myself, but I am completely stuck with creating a possible timer.
Any help appreciated, cheers!
In C++11 there is easy access to timers. For example:
#include <chrono>
#include <iostream>
int main()
{
std::cout << "begin\n";
std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now()
+ std::chrono::minutes(1);
while (std::chrono::steady_clock::now() < tend)
{
// do your game
}
std::cout << "end\n";
}
Your platform may or may not support <chrono> yet. There is a boost implementation of <chrono>.
Without reference to a particular framework or even the OS this is unanswerable.
In SDL there is SDL_GetTicks() which suits the purpose.
On linux, there is the general purpose clock_gettime or gettimeofday that should work pretty much everywhere (but beware of the details).
Win32 API has several function calls related to this, including Timer callback mechanisms, such as GetTickCount, Timers etc. (article)
Using timers is usually closely related to the meme of 'idle' processing. So you'd want to search for that topic as well (and this is where the message pump comes in, because the message pump decides when (e.g.) WM_IDLE messages get sent; Gtk has a similar concept of Idle hooks and I reckon pretty much every UI framework does)
Usually GUI program has so called "message pump" loop. Check of that timer should be a part of your loop:
while(running)
{
if( current_time() > end_time )
{
// time is over ...
break;
}
if( next_ui_message(msg) )
dispatch(msg);
}
Try this one out:
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
See the details at: http://www.programmingtunes.com/creating-timer-c/#sthash.j9WLtng2.dpuf