I have studied and tried to test the ability of libunifex in these days, but I found it does not work as I expected. Here is an example:
#include <unifex/sync_wait.hpp>
#include <unifex/then.hpp>
#include <unifex/when_all.hpp>
#include <unifex/single_thread_context.hpp>
#include <iostream>
int main() {
using namespace unifex;
single_thread_context context;
sender auto s0 = schedule(context.get_scheduler());
sender auto s1 = then(s0, [](){
std::cout << "do complex computation" << std::endl;
});
sender auto s21 = then(s1, [](){});
sender auto s22 = then(s1, [](){});
sync_wait(when_all(s21, s22));
}
In my requirement, I do a complexed computation in s1, so I expect the complexted computation only do once. However, it does the complexed computation twice.
I have two questions:
Is my requirement (make s1 compute once) supported by the paper? (Sorry, the paper is a little complicated for me.)
I found the split function is not implemented yet in libunifex, does it have relation to my requirement?
"Complex computation" have done twice because of you call it twice. The first one is in:
sender auto s21 = then(s1, [](){});
another is in:
sender auto s22 = then(s1, [](){});
Related
I'm using the XLA C++ API, and I've managed to run a simple addition, but I've no idea if I'm doing it right. There seem to be an awful lot of classes that I've not used. Here's my example
auto builder = new XlaBuilder("XlaBuilder");
auto one = ConstantR0(builder, 1);
auto two = ConstantR0(builder, 2);
auto res = one + two;
ValueInferenceMode value_inf_mode;
auto value_inf = new ValueInference(builder_);
auto lit = value_inf
->AnalyzeConstant(res, value_inf_mode)
->GetValue()
->Clone();
// I'm using `untyped_data` because I can't express arbitrary array types.
// I guess I could use `data<int32>` in this simple case
auto data = lit.untyped_data();
std::cout << ((int32*) data)[0] << std::endl; // prints 3
I suspect I didn't actually run that computation through XLA. Here's a different approach based on a sample harness in the XLA source code
XlaComputation computation = res.builder()->Build().ConsumeValueOrDie();
ExecutionProfile profile;
Literal lit = ClientLibrary::LocalClientOrDie()
->ExecuteAndTransfer(computation, {}, nullptr, &profile)
.ConsumeValueOrDie();
data = lit.untyped_data()
Let me start by saying, I am not a skilled C++ programmer, I have just begun that journey and am working in a Win 10 environment using Code::Blocks as my ide. I am starting to learn C++ by coding solutions to the Euler Project problems. I used these problems to start learning Python several years ago, so I have at least one Python solution for the first 50+ problems. In doing these problems in Python, I learned that as my skill improves, I can formulate better solutions. When learning Python, I used a trial & error approach to improving my code until I became aware of the python tools for timing my code. Once, I defined a convenient and consistent timing method, my coding improved dramatically. Since, I am beginning this journey now with C++ I decided I would be proactive and create a consistent method for timing the code execution. To do this, I have decided to utilize the C++ chrono library and have defined two different approaches that seemingly should produce the same time results. However as the tile to this question implies they don't.
So here's my question: Why don't the following two approaches yield the same results?
Approach # 1
This method provides a timing for the do some stuff segment of slightly over 3 seconds, but less than the CODE::BLOCKS execution time report of 3.054 seconds. I certainly understand these differences based on the program flow. So this approach seems to give good result. The issue I have with this approach is I need to copy & paste the timing code into each .cpp file I want to time, which seems sloppy.
Output using this method looks like the following:
Elapsed time in seconds : 3.00053 sec
Process returned 0 (0x0) execution time : 3.151 s
#include <iostream>
#include <chrono>
#include <unistd.h>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
// Functions
TimePoint get_timestamp();
double get_duration(TimePoint, TimePoint);
int main()
{
//auto start = chrono::steady_clock::now();
auto start_t = get_timestamp();
//cout << "Start is of type " << typeid(start).name() << "\n";
// do some stuff
sleep(3);
auto end_t = get_timestamp();
//double tme_secs = chrono::duration_cast<chrono::nanoseconds>(end - start).count()/1000000000.0000;
double tme_secs = get_duration(start_t, end_t)/1000000000;
cout << "Elapsed time in seconds : " << tme_secs << " sec";
return 0;
}
TimePoint get_timestamp(){
return Clock::now();
}
double get_duration(TimePoint start, TimePoint end){
return chrono::duration_cast<chrono::nanoseconds>(end - start).count()*1.00000000;
}
Approach #2
In this approach, I attempted to create a ProcessTime class which could be included in files that I want to time and provide a cleaner method. The problem with this approach is I get timing report in the nano seconds, which does not reflect the process being timed. Here is my implementation of this approach.
output using this method looks like the following:
Elapsed time: 1.1422e+06 seconds
Process returned 0 (0x0) execution time : 3.148 s
ProcessTime.h file
#ifndef PROCESSTIME_H_INCLUDED
#define PROCESSTIME_H_INCLUDED
#include <chrono>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
class ProcessTime{
public:
ProcessTime();
double get_duration();
private:
TimePoint proc_start;
};
#endif // PROCESSTIME_H_INCLUDED
ProcessTime.cpp file
#include "ProcessTime.h"
#include <chrono>
using namespace std;
using Clock = chrono::steady_clock;
using TimePoint = chrono::time_point<Clock>;
ProcessTime::ProcessTime(){
TimePoint proc_start = Clock::now();
}
double ProcessTime::get_duration(){
TimePoint proc_end = Clock::now();
return chrono::duration_cast<chrono::nanoseconds>(proc_end - ProcessTime::proc_start).count()*1.00000000;
}
main.cpp file:
#include <iostream>
#include "ProcessTime.h"
#include <unistd.h>
using namespace std;
int main()
{
ProcessTime timer;
// Do some Stuff
sleep(3);
double tme_secs = timer.get_duration()/1000000000;
cout << "Elapsed time: " << tme_secs << " seconds";
return 0;
}
This is incorrect:
ProcessTime::ProcessTime(){
TimePoint proc_start = Clock::now();
}
You are setting a local variable named proc_start, and then the constructor ends. You did not set the actual member variable of ProcessTime.
One fix (and the preferred method) is to use the member-initialization list:
ProcessTime::ProcessTime() : proc_start(Clock::now()) {}
or if you knew nothing about the member-initialization list, the code would look like this to assign the value.
ProcessTime::ProcessTime(){
proc_start = Clock::now();
}
I am quite new to C/C++. I am trying to call 2 functions at time with return value. I did some research and i came to know that threading is not suitable for this as its quite difficult to get the return value through threading. I am using future library with async for this but its not calling the multiple functions at a time (i have tested it with a sleep() and i saw that it wait for other function to finish to get the return value).Please find code here ,could some please help me by showing a simple code as example?
#include <iostream>
#include <future>
#include <windows.h>
#include <string>
using namespace std;
// a non-optimized way of checking for prime numbers:
string test(string t1)
{
string h = "Hello";
string hh = h+t1;
return hh;
}
string test1(string t2)
{
string hh = "Hello";
string hhh = hh+t2;
return hhh;
}
int main ()
{
string t1 = "Hai test1";
string t2 = "Hai teset2";
future<string> stt = async (test,t1);
future<string> sttt = async (test1,t2);
string re1 = stt.get();
string re2 = sttt.get();
cout << re1 << endl;
cout << re2 << endl;
return 0;
}
You should have consulted some standard library reference:
http://en.cppreference.com/w/cpp/thread/async
As you can see there std::async has an overload which takes an additional launch policy. The std::async you are calling has the following problems:
Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words, f may be executed in another thread or it may be run synchronously when the resulting std::future is queried for a value.
and
If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.
So in the end it depends on your compiler what happens.
The solution is quite simple:
future<string> stt = async (launch::async,test,t1);
future<string> sttt = async (launch::async,test1,t2);
string re1 = stt.get();
string re2 = sttt.get();
Suppose that I have the following code:
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>
int main()
{
boost::thread thd([]{ std::cout << "str \n"; });
boost::this_thread::sleep_for(boost::chrono::seconds(3));
if (thd.try_join_for(boost::chrono::nanoseconds(1)))
{
std::cout << "Finished \n";
}
else
{
std::cout << "Running \n";
}
}
MSVC-12.0 and boost 1.55 gives me the different output each time when I start this program. For example,
str
Finished
str
Finished
str
Running
When I change boost::chrono::nanoseconds to boost::chrono::microseconds the output is looks as expected.
Why? What am I doing wrong? Is it a bug in boost library? Is there a ticket about in in boost bug tracker?
Thanks in advance.
Your program simply has a race, most probably due to the fact that 1 nanosecond is awfully short.
try_join_for is implemented by calling try_join_until, a function that will attempt joining until a certain timepoint has been reached:
// I stripped some unrelated template stuff from the code
// to make it more readable
bool try_join_for(const chrono::duration& rel_time)
{
return try_join_until(chrono::steady_clock::now() + rel_time);
}
bool try_join_until(const chrono::time_point& t)
{
system_clock::time_point s_now = system_clock::now();
bool joined= false;
do {
Clock::duration d = ceil<nanoseconds>(t-Clock::now());
if (d <= Clock::duration::zero())
return false; // in case the Clock::time_point t is already reached
// only here we attempt to join for the first time:
joined = try_join_until(s_now + d);
} while (! joined);
return true;
}
The problem is now that try_join_until will check whether the requested time_point has been reached before attempting the join. As you can see, it needs to perform two other calls to clock::now() and some computation to compare the obtained values to the deadline given by the user. This may or may not be completed before the clock jumps beyond your given 1 nanosecond deadline, resulting in the unpredictability of the output.
Be aware that in general timing dependent code like this is fragile. Even with timeouts in the order of milliseconds, if you get preempted at a bad point during execution and there is a high load on the CPU, you might miss a deadline in rare cases. So be sure to always chose your deadlines carefully and never make assumptions that a deadline will be big enough in all possible cases.
What is wrong with just calling .join()? If you insist you can check before you join:
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>
int main()
{
boost::thread thd([]{ std::cout << "str\n"; });
boost::this_thread::sleep_for(boost::chrono::seconds(3));
if (thd.joinable())
thd.join();
}
Note that the behaviour is Undefined anyway if you fail to join a thread before program exit. Use
futures,
condition variables or
semaphores
to signal job completion if that's what you were trying to monitor.
How can I sleep until next Sunday using boost? Can i convert boost::gregorian::date object to something that boost::this_thread::sleep_until can handle? Is it possible?
#include <boost/date_time.hpp>
int main()
{
boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());
boost::gregorian::greg_weekday next_sunday_date(boost::gregorian::Sunday);
boost::gregorian::date next_weekday_date = next_weekday(current_date, next_sunday_date);
// ...
}
Here's what I came up with.
Note that I made the code generally more readable. This is important, not just for future maintenance, but also because it will allow you to "see the forest for the trees" - in turn allowing you to remember the important concepts mentally.
At least, that helps me.
Edit DyP contributed a way to use sleep_until (which would behave more accurately in rare circumstances, e.g. where the clock would change during the sleep).
#include <boost/date_time.hpp>
#include <boost/date_time/time_clock.hpp>
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
using namespace boost::gregorian;
using boost::posix_time::ptime;
using clock = boost::posix_time::microsec_clock; // or: boost::posix_time::second_clock;
auto today = date(day_clock::local_day());
auto at_sunday = greg_weekday(Sunday);
auto next_sunday = next_weekday(today, at_sunday);
#if 1
auto as_tm = to_tm(next_sunday);
auto as_time_t = mktime(&as_tm);
auto as_time_point = std::chrono::system_clock::from_time_t(as_time_t);
std::this_thread::sleep_until(as_time_point);
#else
auto duration = (ptime(next_sunday) - clock::local_time());
auto msecs = duration.total_milliseconds();
std::cout << msecs << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
#endif
}
See it compiling on Coliru (obviously times out)
This sounds unstable. What if the user turns the computer off or goes into hibernation, or just does a restart?
I would do this in one of two ways:
Add a scheduled task(or whatever the windows/osx terminology is) / cronjob (linux) and set it to run on Sunday.
Add it to autostart and periodically(once per 10/30/60 minutes) check if it's Sunday.
Both ways handle restart/shut off/hibernation better than sleeping for 5 days.