What could be the possible reasons for segmentation fault? - multithreading

The code snippet is following:
ValueMapIter valueIter;
for (valueIter = activeValues->begin(); valueIter !=activeValues->end(); ++valueIter)
{
cout << "Before First" << endl;
cout << "sizeactivevalue:" << activeValues->size() << endl;
cout << "first:" << valueIter->first << "Second:" << valueIter->second << endl;
}
The PROGRAM output while running with gdb is:
The program outputs
Before First
sizeactivevalue:10
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x2aaaac8ad940 (LWP 8346)]
0x000000000043e732 in ValueManager::InsertModValue (this=0xd455c90, Id=4615, PId=7753, eId=1100000010570903, iId=2, inId=44301, pe=830795, t=25, bl=2, ste=3, sde=2)
at /home/pathtofile/valuemanager.cpp:304
304 cout << "first:" << valueIter->first << "Second:" << valueIter->second << endl;
How can it receive a segmentation fault, while I have a local copy of ValueMapIter and it ran on the code correctly previously.
The program is multithreaded; there is only one activeValues map. The snippet is inside the InsertModValues function.
The size of the activeValue map is 10 then How can the iter not have a valid first element ?

Related

Reading and writing different files in their own threads from my main loop in C++11

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.
I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.
I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:
#include <future>
#include <iostream>
#include <string>
bool write_file(const std::string filename)
{
std::cout << "write_file: filename is " << filename << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
std::cout << "write_file: written" << std::endl;
return true;
}
int main(int argc, char* argv[])
{
const std::string filename = "foo.txt";
auto write = std::async(std::launch::async, write_file, filename);
while (true)
{
std::cout << "working..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "write result is " << write.get() << std::endl;
}
}
I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.
I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.
Thank you if you can point me in the right direction.
Molly.
write.get() will wait for the async task to finish. You want to use wait_for() instead:
do {
std::cout << "working...\n";
} while(write.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready);
std::cout << "write result is " << write.get() << "\n";

read variable value in main from thread in c++

I need to have a thread which executes a function in while loop(say increments an int value). In the main I need to have a while loop which executes some function(say a for loop which counts from 0 to 5) and then reads the current value of a variable in the thread. The thread must keep running its own while loop irrespective of whats going on in main. However the value of the thread variable must not change while main reads the variable.
I guess this problem can be solved using atomic. However this is a toy problem in which the variable in the thread is an int. In my actual problem the thread variable if of type Eigen::quaternionf or float[4]. So I need to ensure that the entire Eigen::quaternionf or float[4] is held constant when it is read from main.
The cout in the thread is only for debugging. If the code runs with thread safety, it can be removed. I read from another post that using cout in a thread safe manner may need to write a new wrapper around cout with a mutex. I want to avoid it.
My main concern is reading the variable in correct order in main.
My code fails(today is my first day with multithreading) and is as below along with observed output(selected parts). the code fails to keep the order of the output using cout(garbled output). Also I am not sure that the thread variable is correctly read by the main.
#include <thread>
#include <mutex>
#include <iostream>
int i = 0;
void safe_increment(std::mutex& i_mutex)
{
while(1)
{
std::lock_guard<std::mutex> lock(i_mutex);
++i;
std::cout << "thread: "<< std::this_thread::get_id() << ", i=" << i << '\n';
}
}
int main()
{
std::mutex i_mutex;
std::thread t1(safe_increment, std::ref(i_mutex));
while(1)
{
for(int k =0; k < 5; k++)
{
std::cout << "main: k =" << k << '\n';
}
std::lock_guard<std::mutex> lock(i_mutex);
std::cout << "main: i=" << i << '\n';
}
}
The output(selected parts) I get is
thread: 139711042705152, i=223893
thread: 139711042705152, i=223894
thread: 139711042705152, i=223895
main: i=223895
main: k =0
thread: main: k =1139711042705152
main: k =2
main: k =3
, i=main: k =4
223896
thread: 139711042705152, i=223897
thread: 139711042705152, i=223898
thread: 139711042705152, i=224801
thread: 139711042705152, i=224802
main: i=224802
main: k =0
main: k =1
thread: main: k =2
main: k =3
main: k =4
139711042705152, i=224803
thread: 139711042705152, i=224804
thread: 139711042705152, i=224805
i is properly synchronized with the mutex. well done! obviously this runs until you force it to stop, so when you do find a better way to end execution, be sure to join on your thread.
to fix the garbling, you need to synchronize on std::cout:
int main()
{
std::mutex i_mutex;
std::thread t1(safe_increment, std::ref(i_mutex));
while(1)
{
std::lock_guard<std::mutex> lock(i_mutex);//moved up here to sync on std::cout << k
for(int k =0; k < 5; k++)
{
std::cout << "main: k =" << k << '\n';
}
std::cout << "main: i=" << i << '\n';
if (i > 100) break;
}
t1.join(); //thread will continue and main will wait until it is done
//your thread needs to have some way out of its while(1) as well.
}
the thread can maybe be this:
void safe_increment(std::mutex& i_mutex)
{
while(1)
{
std::lock_guard<std::mutex> lock(i_mutex);
++i;
std::cout << "thread: "<< std::this_thread::get_id() << ", i=" << i << '\n';
if (i > 111) break;
}
}

example for yaml-cpp 0.5.3 in linux

I am pretty new to yaml-cpp. After did tutorials, that tutorials are fine. But When I try to Parse my own yaml file, it's a litte difficult for me. I am confused with "operator" and "node".
yaml file is shown below.
Device:
DeviceName: "/dev/ttyS2"
Baud: 19200
Parity: "N"
DataBits: 8
StopBits: 1
Control:
Kp: 5000
Ki: 8
FVF: 100
VFF: 1962
Could you anyone give me an example to get data from that yaml file? thanks for your help.
Also i followed this question , I can build it. But When I run it, I got Segmentation fault (core dumped)
Code:
#include <yaml-cpp/yaml.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
YAML::Node config = YAML::LoadFile("init.yaml");
//read device
std::string DeviceName = config["Device"][0]["DeviceName"].as<std::string>();
int Baud = config["Device"][1]["Baud"].as<int>();
std::string Parity = config["Device"][2]["Parity"].as<std::string>();
int DataBits = config["Device"][3]["DataBits"].as<int>();
int StopBits = config["Device"][4]["StopBits"].as<int>();
//read control
int Kp = config["Control"][0]["Kp"].as<int>();
int Ki = config["Control"][1]["Ki"].as<int>();
int FVF = config["Control"][2]["FVF"].as<int>();
int VFF = config["Control"][3]["VFF"].as<int>();
cout <<"DeviceName" << DeviceName << endl;
cout <<"Baud" << Baud << endl;
cout <<"Parity" << Parity << endl;
cout <<"DataBits" << DataBits << endl;
cout <<"StopBits" << StopBits << endl;
cout <<"Kp" << Kp << endl;
cout <<"Ki" << Ki << endl;
cout <<"FVF" << FVF << endl;
cout <<"VFF" << VFF << endl;
return 0;
}
your code above results in a bad conversion exception because you access the map items in a wrong way.
instead of
std::string DeviceName = config["Device"][0]["DeviceName"].as<std::string>();
just write
std::string DeviceName = config["Device"]["DeviceName"].as<std::string>();
best regards
robert

How to suspend all other threads inside a separate class function c++

I am working on a final project for a class. This project is to mimic multiple atm's. That is my program already runs. Inside of my main.cpp, I created the threads, for now just two, later on maybe more, They call a class Begin that rand() if customers are going to make a deposit or withdraw and then rand() the amount they are going to use and does this 5 times.
#include "ATM.h"
void main()
{
Begin test1;
test1.manager();
thread first(&Begin::atm, test1);
thread second(&Begin::atm, test1);
first.join();
second.join();
delete resbox::cashbox;
system("pause");
}
I cannot figure out how to suspend my threads created in Main.cpp inside of my observe() function like so:
void watcher::observe()
{
float cash;
if (resbox::cashbox->gettotal() >= resbox::cashbox->getmax())
{
//suspend all other threads
cout << "Please empty cash box it is full! with $"<< resbox::cashbox->gettotal() << endl;
cout << "How much would like to withdraw?" << endl;
cin >> cash;
resbox::cashbox->cashwd(cash);
cout << "This is the amount in the reserve box now is $" << resbox::cashbox->gettotal() << endl;
//resume all other threads
}
if (resbox::cashbox->gettotal() <= 500)
{
//suspend all other threads
cout << "Please fill cashbox it is low, has $" << resbox::cashbox->gettotal() << endl;
cout << "How much would like to add?" << endl;
cin >> cash;
resbox::cashbox->cashdp(cash);
cout << "This is the amount in the reserve box now $" << resbox::cashbox->gettotal() << endl;
//resume all other threads
}
}
Whenever the condition is met for one of the if statements I need to be able to suspend all other threads except the current thread that met the condition. Then after the data is completed before leaving the if statement and observer functions resume all other threads.
I read about the possibility of using SuspendThread, and ResumeThread from here, how to suspend thread. Yet I am having a hard time passing the threads created in main.cpp to the observer function so that I could call those functions. I figured out how to create threads from cplusplus.com, I also notice I could potentially use a mutex locking as refered to from What is the best solution to pause and resume pthreads?
I am using c++ under Microsoft Visual Studio 2015 Community.
This is my first time dealing with threads. For my use which is better, pass the created threads to the observer function, or is there another to pause/suspend and then resume them and how would i do so? Thank you for any advice/help provided.
Currently If I run my program and one of the conditions is met by a thread, the other thread will also meet the same condition and I have to enter the amount to deposit/withdraw twice before the threads continue until each thread has dealt with 5 customers each for a total of 10 customers.
I finally figured out what I needed and what to use thanks to:
Class RWLock
By utilizing this class, inside my project. Then creating a global instance of that class.
Then I added the reader and writer lock and unlocks where it function inside my code the best. Like so:
void Begin::atm() //The main function that makes it easier for threads to
call and run the Program.
{
ATM atm;
int choice, amount;
LARGE_INTEGER cicles;
QueryPerformanceCounter(&cicles);
srand(cicles.QuadPart);
for (int i = 0; i < imax; i++) //mimics a total of 5 customers
{
rw.ReadLock(); //Have to place to read lock here.
choice = rand() % 2; //Randomizes the choice of depositing or withdrawing.
amount = rand() % 5000 + 1; //Randomizes 'the amount of cash that the customers use.
rw.ReadUnlock(); //Read unlock must happen here otherwise it blocks the writers.
rw.WriteLock(); //Must happen here!
if (choice == 0)
{
atm.cashdp(amount);
cout << "\tCustomer depositing $" << amount << endl;
}
else if (choice == 1)
{
atm.cashwd(amount);
cout << "\tCustomer withdrawing $" << amount << endl;
}
else
//error checker against the randomizer for the choice of depsoiting or withdrawing.
cout << "error rand creating wrong number" << endl;
rw.WriteUnlock(); //Must Happen here!
Sleep(5000); // Sleeps the program between customer usage to mimic actual use.
}
}

Different values depending on floating point exception flags set

Short question:
How can setting the _EM_INVALID exception flag on the FPU result in different values?
Long question:
In our project we have turned off floating point exceptions in our Release build, but turned on ZERODIVIDE, INVALID and OVERFLOW using _controlfp_s() in our Debug build. This is in order to catch errors if they are there.
However, we would also like results of numerical calculations (involving optimisation algorithms, matrix inversion, Monte Carlo and all sorts of things) to be consistent between Debug and Release build to make debugging easier.
I would expect that the setting of the exception flags on the FPU should not affect the calculated values - only whether exceptions are thrown or not. But after working backwards through our calculations I can isolate the below code example that shows that there is a difference on the last bit when calling the log() function.
This propagates to a 0.5% difference in the resulting value.
The below code will give the shown program output when adding it to a new solution in Visual Studio 2005, Windows XP and compile in Debug configuration. (Release will give a different output, but that's because the optimiser reuses the result from the first call to log().)
I hope that someone can shed a bit of light on this. Thanks.
/*
Program output:
Xi, 3893f76f, 7.4555176582633598
K, c0a682c7, 7.44466687218
Untouched
x, da8caea1, 0.0014564635732296288
Invalid exception on
x, da8caea2, 0.001456463573229629
Invalid exception off
x, da8caea1, 0.0014564635732296288
*/
#include <float.h>
#include <math.h>
#include <limits>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
unsigned uMaskOld = 0;
errno_t err;
cout << std::setprecision (numeric_limits<double>::digits10 + 2);
double Xi = 7.4555176582633598;
double K = 7.44466687218;
double x;
cout << "Xi, " << hex << setw(8) << setfill('0') << *(unsigned*)(&Xi) << ", " << dec << Xi << endl;
cout << "K, " << hex << setw(8) << setfill('0') << *(unsigned*)(&K) << ", " << dec << K << endl;
cout << endl;
cout << "Untouched" << endl;
x = log(Xi/K);
cout << "x, " << hex << setw(8) << setfill('0') << *(unsigned*)(&x) << ", " << dec << x << endl;
cout << endl;
cout << "Invalid exception on" << endl;
::_clearfp();
err = ::_controlfp_s(&uMaskOld, 0, _EM_INVALID);
x = log(Xi/K);
cout << "x, " << hex << setw(8) << setfill('0') << *(unsigned*)(&x) << ", " << dec << x << endl;
cout << endl;
cout << "Invalid exception off" << endl;
::_clearfp();
err = ::_controlfp_s(&uMaskOld, _EM_INVALID, _EM_INVALID);
x = log(Xi/K);
cout << "x, " << hex << setw(8) << setfill('0') << *(unsigned*)(&x) << ", " << dec << x << endl;
cout << endl;
return 0;
}
This is not a complete answer, but it is too long for a comment.
I suggest you isolate the code that does the questionable calculations and put it in a subroutine, preferably in a source module that is compiled separately. Something like:
void foo(void)
{
double Xi = 7.4555176582633598;
double K = 7.44466687218;
double x;
x = log(Xi/K);
…Insert output statements here…
}
Then you would call the routine with different settings:
cout << "Untouched:\n";
foo();
cout << "Invalid exception on:\n";
…Change FP state…
foo();
This guarantees that the same instructions are executed in each case, eliminating the possibility that the compiler has for some reason generated separate code for each sequence. The way you have compiled the code, I suspect it is possible the compiler may have used 80-bit arithmetic in one case and 64-bit arithmetic in another, or may have used 80-bit arithmetic generally but converted some result to 64-bit in one case but not another
Once that is done, you can partition and isolate the code further. E.g., try evaluating Xi/K once before any of the tests, storing that in a double, and passing it to foo as a parameter. The tests whether the log call differs depending on the floating-point state. I suspect that is the case, as it is unlikely the division operation would differ.
Another advantage of isolating the code this way is that you could step through it in the debugger to see exactly where behavior diverges. You could step through it, one instruction at a time, with different floating-point states simultaneously in two windows and examine the results at each step to see exactly where the divergence is. If there is no divergence by the time you reach the log call, you should step through that, too.
Incidental notes:
If you know Xi and K are close to each other, it is better to compute log(Xi/K) as log1p((Xi-K)/K). When Xi and K are close to each other, the subtraction Xi-K is exact (has no error), and the quotient has more useful bits (the 1 that we already knew about and some zero bits following it are gone).
The fact that slight changes in your floating-point environment cause a .5% change in your result implies your calculations are very sensitive to error. This suggests that, even if you make your results reproducible, the errors that necessarily exist in floating-point arithmetic cause your result to be inaccurate. That is, the final error will still exist, it just will not be called to your attention by the difference between two different ways of calculating.
It appears in your C++ implementation that unsigned is four bytes but double is eight bytes. So printing the encoding a double by aliasing it to an unsigned omits half of the bits. Instead, you should convert a pointer to the double to a pointer to const char and print sizeof(double) bytes.

Resources