Multithreaded application with gtkD - multithreading

I'm playing with gtkD for a while, and I'm learning D2/Phobos in parallel. Yesterday I was looking up the std.concurrency module and tried to write a toy multithreaded fractal viewer, but the problem is that I can't see the way multithreading works with gtkD.
Now, I have this:
import std.concurrency;
class TestMainWindow : MainWindow
{
this() {
super("test");
...
spawn(&worker);
}
public void notify() {
m_progress.pulse();
}
private ProgressBar m_progress;
}
shared(TestMainWindow) window;
main(string[] args) {
Main.init(args);
window = new shared(TestMainWindow)();
Main.run();
}
void worker() {
for (int i = 0; i < 20; ++i) {
(cast(TestMainWindow) window).notify();
Thread.sleep(dur!"msecs"(200));
}
}
In the Andrei's book, in the chapter for concurrency, there's the message passing paradigm, which I want to
apply, but the problem is that the gtk main loop is hidden from me. I don't like the above code, because its
ugly to cast to non-shared and likely unsafe.
So is there some way to inherit a "thread-agnostic" class, making it thread-aware, and what is the
standard mechanism in gtkD to program multithreaded applications? I've seen the gthread.Thread module,
but its role seems to be only as an interface to the external C gtk+ threading capabilities.

Unfortunately I'm pretty sure the answer is no. GtkD was designed before shared existed and supports both D1 and D2. Furthermore, shared is so buggy it's not usable yet. Therefore, GtkD doesn't support shared and probably won't for a while.

Related

Permanent Threads in QT

I'm new in QT...and i haven't time. I have a GUI with 3 labels that must be update from 3 different threads (permanents, that invoke 3 different methods) every 10 secs. What is the best way to make this? thanks in advance!
You should use Qt signaling mechanism.
class QWindow : QMainWindow
{
//this macro is important for QMake to let the meta programming mechanism know
//this class uses Qt signalling
Q_OBJECT
slots:
void updateLabel(QString withWhat)
...
};
And now You just need to connect this slot to some signal
class SomeThreadClass : QObject
{
Q_OBJECT
...
signals:
void labelUpdateRequest(QString withwhat);
};
in the constructor of the window
QWindow::QWindow(QWidget* parent) : QMainWindow(parent)
{
m_someThread = new SomeThreadClass();
//in old style Qt, now there's a mechanism for compile time check
//don't use pointers, you need to free them at some point and there might be many receivers
//that might use it
connect(m_someThread, SIGNAL(labelUpdateRequest(QString)), this, SLOT(updateLabel(QString));
...
}
now just at some point in the thread:
SomeThreadClass::someMethod()
{
//do something...
emit labelUpdateRequest(QString("Welcome to cartmanland!"));
//this will be received by all classes that call connect to this class.
}
Hope that helps :)

Thread-Safe Properties in C#

I know that this subject is slightly "Played Out", but I am still terribly confused. I have a class with properties that will be updates by multiple threads and I am trying to allow the properties to be updated in a Threadsafe manner.
Below, I have included a few examples of what I have tried thus far (the class is contained within a BindingList so its properties call a PropertyChangingEventHandler event).
Method 1 - Doubles
private double _Beta;
public double Beta
{
get
{
return _Beta;
}
}
private readonly BetaLocker = new object();
public void UpdateBeta(double Value)
{
lock (BetaLocker)
{
_Beta = Value;
NotifyPropertyChanged("Beta");
}
}
Method 2 - Ints
private int _CurrentPosition;
public int CurrentPosition
{
get
{
return _CurrentPosition;
}
}
public void UpdatePosition(int UpdateQuantity)
{
Interlocked.Add(ref _CurrentPosition, UpdateQuantity);
NotifyPropertyChanged("CurrentPosition");
}
Basically - is the current way that I am creating properties completely threadsafe for both ints and doubles?
You have to ask yourself what it means to be Thread Safe (yes, it's a link to wikipedia and it's blacked out ^_^):
A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. There are various strategies for making thread-safe data structure
So now you have to determine if your code guarantees safe execution if executed by multiple threads: the quick answer is that both of your code samples are thread safe! However (and this is a big one), you also have to consider the usage of the object and determine if it is Thread Safe also... here is an example:
if(instance.Beta==10.0)
{
instance.UpdateBeta(instance.Beta*10.0);
}
// what's instance.Beta now?
In this case you have absolutely no guarantee that Beta will be 100.0 because beta could have changed after you checked it. Imagine this situation:
Thread 2: UpdateBeta(10.0)
Thread 1: if(Beta == 10.00)
Thread 2: UpdateBeta(20.0)
Thread 1: UpdateBeta(Beta*10.0)
// Beta is now 200.0!!!
The quick and dirty way to fix this is to use a double-checked lock:
if(instance.Beta==10.0)
{
lock(instance)
{
if(instance.Beta==10.0)
{
instance.UpdateBeta(instance.Beta*10.0);
}
}
}
The same is true for CurrentPosition.

Is it possible to launch boost thread on a non static member function from other memeber function

like you probably know boost thread requires that memeber function that is fwd as argument must be static. There is a bind way to do it if it is not static, but I prefer the Object o; o.startThread() than
Object o;
boost::thread(boost::bind....) because it keeps the thread code inside the class(also exception handling).
So for example can this be rewritten to work:
class sayHello
{
string name;
public:
sayHello(string name_):name(name_)
{
}
void repeatHello()
{
while (true)
{
boost::this_thread::sleep(posix_time::seconds(3));
cout<<"Hello "<<name<<endl;
}
}
void infiniteRun()
{
boost::thread thr(repeatHello);//broken line
}
};
P.S. for people wandering what is the "bind way" AFAIK it is this:
sayHello sh("world");
boost::thread thr(boost::bind(&sayHello::repeatHello,&sh));
Yes...
void infiniteRun()
{
boost::thread thr(boost::bind(&sayHello::repeatHello,this));
}
Although doing it that way fraught with danger of memory leaks and access violations. When dealing with threads, I would highly recommend using smart pointers to keep things alive correctly.

QFuture that can be cancelled and report progress

The QFuture class has methods such as cancel(), progressValue(), etc. These can apparently be monitored via a QFutureWatcher. However, the documentation for QtConcurrent::run() reads:
Note that the QFuture returned by
QtConcurrent::run() does not support
canceling, pausing, or progress
reporting. The QFuture returned can
only be used to query for the
running/finished status and the return
value of the function.
I have looked in vain for what method actually can create a QFuture that can be cancelled and report progress for a single long-running operation. (It looks like maybe QtConcurrent::map() and similar functions can, but I just have a single, long-running method.)
(For those familiar with .Net, something like the BackgroundWorker class.)
What options are available?
Though it's been a while since this question was posted and answered I decided to add my way of solving this problem because it is rather different from what was discussed here and I think may be useful to someone else. First, motivation of my approach is that I usually don't like to invent own APIs when framework already has some mature analogs. So the problem is: we have a nice API for controlling background computations represented by the QFuture<>, but we have no object that supports some of the operations. Well, let's do it. Looking on what's going on inside QtConcurrent::run makes things much clearer: a functor is made, wrapped into QRunnable and run in the global ThreadPool.
So I created generic interface for my "controllable tasks":
class TaskControl
{
public:
TaskControl(QFutureInterfaceBase *f) : fu(f) { }
bool shouldRun() const { return !fu->isCanceled(); }
private:
QFutureInterfaceBase *fu;
};
template <class T>
class ControllableTask
{
public:
virtual ~ControllableTask() {}
virtual T run(TaskControl& control) = 0;
};
Then, following what is made in qtconcurrentrunbase.h I made q-runnable for running this kind of tasks (this code is mostly from qtconcurrentrunbase.h, but slightly modified):
template <typename T>
class RunControllableTask : public QFutureInterface<T> , public QRunnable
{
public:
RunControllableTask(ControllableTask<T>* tsk) : task(tsk) { }
virtial ~RunControllableTask() { delete task; }
QFuture<T> start()
{
this->setRunnable(this);
this->reportStarted();
QFuture<T> future = this->future();
QThreadPool::globalInstance()->start(this, /*m_priority*/ 0);
return future;
}
void run()
{
if (this->isCanceled()) {
this->reportFinished();
return;
}
TaskControl control(this);
result = this->task->run(control);
if (!this->isCanceled()) {
this->reportResult(result);
}
this->reportFinished();
}
T result;
ControllableTask<T> *task;
};
And finally the missing runner class that will return us controllable QFututre<>s:
class TaskExecutor {
public:
template <class T>
static QFuture<T> run(ControllableTask<T>* task) {
return (new RunControllableTask<T>(task))->start();
}
};
The user should sublass ControllableTask, implement background routine which checks sometimes method shouldRun() of TaskControl instance passed to run(TaskControl&) and then use it like:
QFututre<int> futureValue = TaskExecutor::run(new SomeControllableTask(inputForThatTask));
Then she may cancel it by calling futureValue.cancel(), bearing in mind that cancellation is graceful and not immediate.
I tackled this precise problem a while ago, and made something called "Thinker-Qt"...it provides something called a QPresent and a QPresentWatcher:
http://hostilefork.com/thinker-qt/
It's still fairly alpha and I've been meaning to go back and tinker with it (and will need to do so soon). There's a slide deck and such on my site. I also documented how one would change Mandelbrot to use it.
It's open source and LGPL if you'd like to take a look and/or contribute. :)
Yan's statement is inaccurate. Using moveToThread is one way of achieving the proper behavior, but it not the only method.
The alternative is to override the run method and create your objects that are to be owned by the thread there. Next you call exec(). The QThread can have signals, but make sure the connections are all Queued. Also all calls into the Thread object should be through slots that are also connected over a Queued connection. Alternatively function calls (which will run in the callers thread of execution) can trigger signals to objects that are owned by the thread (created in the run method), again the connections need to be Queued.
One thing to note here, is that the constructor and destructor are running in the main thread of execution. Construction and cleanup need to be performed in run. Here is an example of what your run method should look like:
void MythreadDerrivedClass::run()
{
constructObjectsOnThread();
exec();
destructObjectsOnThread();
m_waitForStopped.wakeAll();
}
Here the constructObjectsOnThread will contain the code one would feel belongs in the constructor. The objects will be deallocated in destructObjectsOnThread. The actual class constructor will call the exit() method, causing the exec() to exit. Typically you will use a wait condition to sit in the destructor till the run has returned.
MythreadDerivedClass::~MythreadDerivedClass()
{
QMutexLocker locker(&m_stopMutex);
exit();
m_waitForStopped.wait(locker.mutex(), 1000);
}
So again, the constructor and destructor are running in the parent thread. The objects owned by the thread must be created in the run() method and destroyed before exiting run. The class destructor should only tell the thread to exit and use a QWaitCondition to wait for the thread to actually finish execution. Note when done this way the QThread derived class does have the Q_OBJECT macro in the header, and does contain signals and slots.
Another option, if you are open to leveraging a KDE library, is KDE's Thread Weaver. It's a more complete task based multitasking implementation similar QtConcurrentRun in that it leverages a thread pool. It should be familiar for anyone from a Qt background.
That said, if you are open to a c++11 method of doing the same thing, I would look at std::async. For one thing, you will no longer have any dependance on Qt, but the api also makes more clear what is going on. With MythreadDerivedClass class inheriting from QThread, the reader gets the impression that MythreadDerivedClass is a thread (since it has an inheritance relationship), and that all its functions run on a thread. However, only the run() method actually runs on a thread. std::async is easier to use correctly, and has fewer gotcha's. All our code is eventually maintained by someone else, and these sorta things matter in the long run.
C++11 /w QT Example:
class MyThreadManager {
Q_OBJECT
public:
void sndProgress(int percent)
void startThread();
void stopThread();
void cancel() { m_cancelled = true; }
private:
void workToDo();
std::atomic<bool> m_cancelled;
future<void> m_threadFuture;
};
MyThreadedManger::startThread() {
m_cancelled = false;
std::async(std::launch::async, std::bind(&MyThreadedManger::workToDo, this));
}
MyThreadedManger::stopThread() {
m_cancelled = true;
m_threadfuture.wait_for(std::chrono::seconds(3))); // Wait for 3s
}
MyThreadedManger::workToDo() {
while(!m_cancelled) {
... // doWork
QMetaInvoke::invokeMethod(this, SIGNAL(sndProgress(int)),
Qt::QueuedConnection, percentDone); // send progress
}
}
Basically, what I've got here isn't that different from how your code would look like with QThread, however, it is more clear that only workToDo() is running on the thread and that MyThreadManager is only managing the thread and not the thread itself. I'm also using MetaInvoke to send a queued signal for sending our progress updates with takes care of the progress reporting requirement. Using MetaInvoke is more explicit and always does the right thing (doesn't matter how you connect signals from your thread managers to other class's slots). You can see that the loop in my thread checks an atomic variable to see when the process is cancelled, so that handles the cancellation requirement.
Improve #Hatter answer to support Functor.
#include <QFutureInterfaceBase>
#include <QtConcurrent>
class CancellationToken
{
public:
CancellationToken(QFutureInterfaceBase* f = NULL) : m_f(f){ }
bool isCancellationRequested() const { return m_f != NULL && m_f->isCanceled(); }
private:
QFutureInterfaceBase* m_f;
};
/*== functor task ==*/
template <typename T, typename Functor>
class RunCancelableFunctorTask : public QtConcurrent::RunFunctionTask<T>
{
public:
RunCancelableFunctorTask(Functor func) : m_func(func) { }
void runFunctor() override
{
CancellationToken token(this);
this->result = m_func(token);
}
private:
Functor m_func;
};
template <typename Functor>
class RunCancelableFunctorTask<void, Functor> : public QtConcurrent::RunFunctionTask<void>
{
public:
RunCancelableFunctorTask(Functor func) : m_func(func) { }
void runFunctor() override
{
CancellationToken token(this);
m_func(token);
}
private:
Functor m_func;
};
template <class T>
class HasResultType
{
typedef char Yes;
typedef void *No;
template<typename U> static Yes test(int, const typename U::result_type * = 0);
template<typename U> static No test(double);
public:
enum { Value = (sizeof(test<T>(0)) == sizeof(Yes)) };
};
class CancelableTaskExecutor
{
public:
//function<T or void (const CancellationToken& token)>
template <typename Functor>
static auto run(Functor functor)
-> typename std::enable_if<!HasResultType<Functor>::Value,
QFuture<decltype(functor(std::declval<const CancellationToken&>()))>>::type
{
typedef decltype(functor(std::declval<const CancellationToken&>())) result_type;
return (new RunCancelableFunctorTask<result_type, Functor>(functor))->start();
}
};
User example:
#include <QDateTime>
#include <QDebug>
#include <QTimer>
#include <QFuture>
void testDemoTask()
{
QFuture<void> future = CancelableTaskExecutor::run([](const CancellationToken& token){
//long time task..
while(!token.isCancellationRequested())
{
qDebug() << QDateTime::currentDateTime();
QThread::msleep(100);
}
qDebug() << "cancel demo task!";
});
QTimer::singleShot(500, [=]() mutable { future.cancel(); });
}
For a long running single task, QThread is probably your best bet. It doesn't have build-in progress reporting or canceling features so you will have to roll your own. But for simple progress update it's not that hard. To cancel the task, check for a flag that can be set from calling thread in your task's loop.
One thing to note is if you override QThread::run() and put your task there, you can't emit signal from there since the QThread object is not created within the thread it runs in and you can't pull the QObject from the running thread. There is a good writeup on this issue.

How to forward overloaded constructor call to another constructor in C++/CLI

I know that there is no way to do this in pure C++, but I was wondering if it is possible to call a constructor from another constructor's initialization list in C++/CLI, same way one can do it in C#.
Example:
ref class Foo {
Foo() {}
Foo(int i) : Foo() {}
}
It is called a "delegating constructor". It is not available in the language yet. But there's a formal proposal, you'll find it in annex F.3.1 of the language specification. Given Microsoft's stance towards C++/CLI, that is unlikely to see the light of day anytime soon.
UPDATE: delegating constructors did have a life beyond the proposal in that annex, they were added to the standard C++11 language specification. Microsoft has been working on getting the C++11 additions implemented. Delegating constructors finally made it for VS2013. And they also work in C++/CLI in that edition.
You can do following
ref class A
{
public:
A(int p) : p(p) { this->A::A(); }
A() : p(1) {}
int p;
};
It is not valid C++ code , but VC compiles it fine :)
Just stumbled by, for the same question. In my case I'm using VS2010.
It is clear that VS2010 will never get updated to fully implement C++11, use VS2015 if you need better compliance with the standard (which I do when I can). But for some (legacy) projects I still have to use VS2010.
An approach that works in many cases (for me) is the use of a private function with all shared initialisation code in it. Example:
class A
{
private:
void Inidialise() { /* common initialisation here */ }
public:
A() { Initialise(); /* specific initialisation for A() here */ }
A(bool a) { Initialise(); /* specific initialisation for A(bool) here */ }
A(int b) { Initialise(); /* specific initialisation for A(int) here */ }
/* etcetera */
}
It does not solve all 'problems' and it does not prevent all cases of duplicate code but it goes a long way.
When you said "I know that there is no way to do this in pure C++" you were in error. It is possible to do that in native C++. You can use the placement new operator to do so.
class A
{
public:
A(int p) : p(p)
{ new(this)A(); }
A() : p(1) {}
int p;
};

Resources