Terminate current thread - c++11

How can I cleanly terminate the current child std::thread in C++11? The decision to terminate is made at a function call depth of 4 or 5 from the main thread method so I don't want to check whether I should terminate at each return. I have looked at exit and terminate but it looks like they terminate the entire process and not just the current thread.
For instance:
void A() { B(); ... }
void B() { C(); ... }
void C() { D(); ... }
void D() { /* oops! need to terminate this thread*/ }
void main() {
thread t(A);
}

An alternative would be to use std::async and throw an exception from the thread you wish to terminate. Then you could call get() on the future returned by your async call to retrieve the exception and terminate gracefully. Something like this, for example:
#include <iostream>
#include <thread>
#include <future>
void A();
void B();
void C();
void D();
void A() { while (true) B(); }
void B() { while (true) C(); }
void C() { while (true) D(); }
void D() { throw -1; }
int main()
{
auto future = std::async(A);
try {
future.get();
}
catch (int e) {
// Handle thread termination
std::cout << "Thread threw exception " << e << '\n';
}
std::cout << "Application terminating..." << '\n';
return 0;
}

Related

QtConcurrent::run() calling another class method

I am trying to use QTConcurrent class to launch some tasks asynchronously but I am getting some errors:
This is my code:
class A {
public:
void method1();
};
class B {
std::unique_ptr<A> ptr;
public:
void method2() {
QtConcurrent::run(&this->ptr, &A::method1);
}
}
I get compilation error.
Could someone tell me what the correct syntax is?
Thanks in advance and regards
I finally was able to find working version:
class A {
public:
void method1();
};
class B {
std::unique_ptr<A> ptr;
public:
void method2() {
QtConcurrent::run(this->ptr.get(), &A::method1);
}
}

Passing member function that accepts Base type to class that owns Derived type

Example
In example above I've tried to store pointer-to-member_function of the overloaded function in the template-based class.
The problem is that overloaded function uses Base class as parameter and current class is template class from Derived class.
Handlers
#include <iostream>
#include <string>
class HandlerA
{
public:
void foo(const std::string& m)
{
std::cout << "HandlerA: " << m << '\n';
}
};
class IBaseHandlerB
{
public:
virtual void bar(const std::string& m) = 0;
};
class HandlerB : public IBaseHandlerB
{
public:
virtual void bar(const std::string& m) override
{
std::cout << "HandlerB: " << m << '\n';
}
};
Events
class Event
{
public:
virtual void write(HandlerA&) const = 0;
virtual void write(IBaseHandlerB&) const = 0;
};
class FancyEvent : public Event
{
public:
virtual void write(HandlerA& h) const override
{
h.foo("FancyEvent");
}
virtual void write(IBaseHandlerB& h) const override
{
h.bar("FancyEvent");
}
};
Wrapper and usage example
template <typename T, typename Event>
class HandlerWrapper
{
public:
HandlerWrapper(T&& handler, void(Event::*func)(T&) const)
: m_handlerImpl(std::forward<T>(handler))
, m_eventFn(func) {}
void call(const Event& event)
{
(event.*m_eventFn)(m_handlerImpl);
}
private:
T m_handlerImpl;
void(Event::*m_eventFn)(T&) const;
};
// ------- Usage -------
int main(void)
{
FancyEvent event;
// OK
HandlerWrapper<HandlerA, Event> h(HandlerA(), &Event::write);
h.call(event);
// Error: Candidate constructor not viable: no overload of
// 'writeWithHandler' matching
// 'void (LogEvent::*)(CEFEventHandler &) const' for 2nd argument
HandlerWrapper<HandlerB, Event> h2(HandlerB(), &Event::write);
h2.call(event);
return 0;
}
Question
How to specify correct template type to accept function-to-Base if class template argument is derived from that Base?
My goal is to pass just pointer-to-member_function to another class whenever that class is the same with type that function accepts or derived from it.

Performance test:singleton class with and without double check locking

I have two implementations of singleton classes
public class Test2 {
private static Test2 _instance=new Test2();
private Test2(){
}
public static synchronized Test2 getInstance(){
if(_instance == null){
_instance = new Test2();
}
return _instance;
}
}
And:
public class TestSingleton {
private static TestSingleton _instance=new TestSingleton();
private TestSingleton(){
}
public static TestSingleton getInstance(){
if (_instance == null) {
synchronized (TestSingleton.class) {
if (_instance == null) {
_instance = new TestSingleton();
}
}
}
return _instance;
}
I want to parametrize my finding in terms of time taken, what I did is this:
Callable<Long> task = new Callable<Long>() {
#Override
public Long call() throws Exception {
long start = System.nanoTime();
**TestSingleton.getInstance();**
long end = System.nanoTime();
return end - start;
}
};
for (int i = 0; i < 100000; i++) {
futList.add(es1.submit(task));
}
for (Future<Long> fut : futList) {
try {
totalTime1.getAndAdd(fut.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Time taken by S1 " + totalTime1.get());
.
.
ExecutorService es2 = Executors.newFixedThreadPool(threadpool);
Callable<Long> task1 = new Callable<Long>() {
#Override
public Long call() throws Exception {
long start = System.nanoTime();
Test2.getInstance();
long end = System.nanoTime();
return end - start;
}
};
for (int i = 0; i < 100000; i++) {
futList1.add(es2.submit(task1));
}
for (Future<Long> fut : futList1) {
try {
totalTime2.getAndAdd(fut.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Time taken by S2 " + totalTime2.get());
The results I got is:
Time taken by S1 4636498
Time taken by S2 5127865
First question is this the correct approach? and second even if I comment the getinstances method in both the call(), I get different times of execution of two identical blocks:
Time taken by S1 1506640
Time taken by S2 2156172
Don't measure each execution and sum the times, there will be too much inaccuracy in the individual measurements. Instead, get start time, execute 100000 times, get end time. Also, execute a few 1000 times before you start measuring to avoid skewing by start-up costs.

Why different result each run?

I'm playing around with CompletableFuture and streams in Java 8 and I get different printouts each time I run this. Just curious, why?
public class DoIt {
public static class My {
private long cur = 0;
public long next() {
return cur++;
}
}
public static long add() {
long sum = 0;
for (long i=0; i<=100;i++) {
sum += i;
}
return sum;
}
public static long getResult(CompletableFuture<Long> f) {
long l = 0;
try {
f.complete(42l);
l = f.get();
System.out.println(l);
} catch (Exception e) {
//...
}
return l;
}
public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(2);
My my = new My();
long sum = Stream.generate(my::next).limit(20000).
map(x -> CompletableFuture.supplyAsync(()-> add(), exec)).
mapToLong(f->getResult(f)).sum();
System.out.println(sum);
exec.shutdown();
}
}
If I skip the f.complete(42l) call I always get the same result.
http://download.java.net/jdk8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-
by the time the complete(42l) call happens, some add()'s may have already completed.

Runtime polymorphism in C++

I have an interface, and I was trying an example on dynamic polymorphism as follows:
#include <iostream>
using namespace std;
class foo{
public:
virtual void set();
virtual void printValue();
};
class fooInt : public foo{
private:
int i;
public:
int get(){
return i;
}
void set(int val){ //override the set
i = val;
}
void printValue(){
cout << i << endl;
}
};
int main(){
foo *dt; //Create a base class pointer
dt = new fooInt; //Assign a sub class reference
dt->set(9);
}
However when I compile this, I get no matching function for call to ‘foo::set(int)’. Where am I going wrong? I tried to read this article, and I still couldn't figure out the mistake.
class foo has no method set(int). It has a method set(), but no method set(int).
If you intend to override an inherited method, the superclass method and your method must have the same signature:
class foo {
...
// If you really want an abstract class, the `= 0`
// ensures no instances can be created (makes it "pure virtual")
virtual void set(int) = 0;
...
}
This is because your definition of
virtual void set();
Should be
virtual void set(int val);
The corrected program is given here
#include <iostream>
using namespace std;
class foo {
public:
virtual void set(int val)=0;////////here you have void set() function with no argument but you tried to override void set(int val) which take one argument.
virtual void printValue()=0;
};
class fooInt : public foo{
private:
int i;
public:
fooInt()
{
cout<<"constructor called\n";
}
int get(){
return i;
}
void set(int val){ //override the set
i = val;
}
void printValue(){
cout << i << endl;
}
};
int main(){
foo *dt; //Create a base class pointer
dt=new fooInt;
dt->set(9);
dt->printValue();
}
Fault of the previous program were
1.You tried to override set() {no argument} with set(int val){one argument}.
2.When a class contain a pure virtual function,it must be implemented by its derived classes.
3. No object can be created of a class which contain a pure virtual function.But ref can be created.
Thanks

Resources