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

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";

Related

How to scan strings with spaces in cpp in a new line?

enter image description here3(no of cases)
hello world
a b c d
data structures and algorithms.
Let say above is the given input format.Each string starts in a new line.Can i know how to read in the above way in cpp.I tried with getline function.It didn't work.
The getline method should work just fine. The following code works fine.
#include <iostream>
using namespace std;
int main(){
string s[3];
getline(cin, s[0]);
getline(cin, s[1]);
getline(cin, s[2]);
cout << s[0] << endl << s[1] << endl << s[2];
return 0;
}
EDIT:
After your clarification, it seems that the problem is actually that the buffer is not being cleared properly. So just use cin.ignore(); after cin >> t;
Refer to the code below:
#include <iostream>
using namespace std;
int main(){
int t;
cin >>t;
cin.ignore(); // This should clear the input buffer
string s;
getline(cin, s);
cout << s << endl;
return 0;
}

What is the difference between two join statements in the code?

In the below code, there are two joins (of course one is commented). I would like to know what is the difference between
when join is executed before the loop and when join is executed after the loop?
#include <iostream>
#include <thread>
using namespace std;
void ThreadFunction();
int main()
{
thread ThreadFunctionObj(ThreadFunction);
//ThreadFunctionObj.join();
for (int j=0;j<10;++j)
{
cout << "\tj = " << j << endl;
}
ThreadFunctionObj.join();
return 0;
}
void ThreadFunction()
{
for (int i=0;i<10;++i)
{
cout << "i = " << i << endl;
}
}
A join() on a thread waits for it to finish execution, your code doesn't continue as long as the thread isn't done. As such, calling join() right after starting a new thread defeats the purpose of multi-threading, as it would be the same as executing those two for loops in a serial way. Calling join() after your loop in main() ensures that both for loops execute in parallel, meaning that at the end of your for loop in your main(), you wait for the ThreadFunction() loop to be done too. This is the equivalent of you and a friend going out to eat, for example. You both start eating at relatively the same time, but the first one to finish still has to wait for the other (might not be the best example, but hope it does the job).
Hope it helps

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

how to convert mpf_class to String

Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.
Basically what I did was:
std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));
As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks
Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.
Here is my code
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
int main(void) {
mpf_class a;
a = 3141592653589793.2;
std::cout << a << std::endl;
// Outputs 3.14159e+15
std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
// Outputs +3.14E+15
}
Then you can use an std::ostringstream object instead of std::cout.
Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html

C++ Delete Error -- _unlock_fhandle throwing exception?

I have a straightforward problem but I don't understand why I have it.
I would greatly appreciate any insight.
I wrote this code to test that I was correctly creating and using DLLs in Visual Studio 2010 under Win 7 64bit that could execute on Windows XP. The code executes correctly, and because it is a small test program freeing the allocated memory is not critical, but certainly will be in the future.
I am implicitly calling the DLL, as I say, it appears to work just fine. When I add the line "delete dllMsg;" to toyUseDLL.cpp it crashes, and the debugger shows _unlock_fhandle in osfinfo.c.
If it's relevant I am compiling the program with /MT to embed the runtime library (for a small handful of not important reasons).
It seems pretty obvious that I'm deallocating something not allocated, but the program output is correct since the pointers are passing the referenced memory locations. The only thing I can think of is that my pointer isn't valid, and it's only working by pure chance that the memory wasn't overwritten.
Thanks for any help, I'm pretty new to C++ and have already found a lot of great help on this site, so thanks for everyone who has posted in the past!! :-)
msgDLL.h
#include <string>
using namespace std;
namespace toyMsgs {
class myToyMsgs {
public:
static __declspec(dllexport) string* helloMsg(void);
static __declspec(dllexport) string* goodbyeMsg(void);
};
}
msgDLL.cpp
#include <iostream>
#include <string>
#include "msgDLL.h"
using namespace std;
namespace toyMsgs {
string* myToyMsgs::helloMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Hello from the DLL");
cout << "Here in helloMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
string* myToyMsgs::goodbyeMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Good bye from the DLL");
cout << "Here in goodbyeMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
}
toyUseDLL.cpp
#include <iostream>
#include <string>
#include "stdafx.h"
#include "msgDLL.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
string myMsg;
string *dllMsg;
myMsg.assign ("This is a hello from the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::helloMsg();
cout << "Saying Hello? " << *(dllMsg) << endl;
delete dllMsg;
myMsg.assign ("This is the middle of the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::goodbyeMsg();
cout << "Saying goodbye? " << *(dllMsg) << endl;
myMsg.assign ("This is a goodbye from the toy program");
cout << myMsg << endl;
return 0;
}
Program Output:
This is a hello from the toy program
Here in helloMsg, dllMsg is: "Hello from the DLL"
Saying Hello? Hello from the DLL
This is the middle of the toy program
Here in goodbyeMsg, dllMsg is: "Good bye from the DLL"
Saying goodbye? Good bye from the DLL
This is a goodbye from the toy program
The problem is that you are using /MT to compile your EXE and DLL. When you use /MT, each executable gets its own copy of the C runtime library, which is a separate and independent context. CRT and Standard C++ Library types can't safely be passed across the DLL boundary when both DLLs are compiled /MT. In your case the string is allocated by one CRT (on its private OS Heap), and freed by the EXE (which has a different heap) causing the crash in question.
To make the program work, simply compile /MD.
General advice: /MT is almost never the right thing to do (for a large handful of relatively important reasons including memory cost, performance, servicing, security and others).
Martyn
There is some good analysis here Why does this program crash: passing of std::string between DLLs

Resources