The "this" pointer and message receiving in D - multithreading

The D multithreading model disallows implicit memory sharing, preferring message passing and immutable data. However, the compiler seems to be odd about letting a this pointer through when receiving messages:
import std.concurrency;
import std.stdio;
class Wat {
int foo;
Tid workerThread;
this(int f)
{
foo = f;
workerThread = spawn(&threadedWork);
}
// Must be static. This makes sense because otherwise
// the object (via "this") would be accessible in two threads,
// and D discourages shared memory,
// preferring messages and immutable data.
static void threadedWork()
{
// Compiler correctly complains that I can't access a non-static function
// from inside a static one.
bar(42);
while (true) {
// But this is allowed. What gives?
receive (
&bar
);
}
}
void bar(int bar)
{
if (foo == bar)
writeln("The answer");
}
}
Why is the compiler allowing me to use a non-static function inside receive? Is this a bug?

Looks like a bug. What happens is &bar gets you a pointer to the method WITHOUT this which has type as a function pointer:
pragma(msg, typeof(&Wat.bar));
void function(int bar)
std.concurrency.receive then sees that and says "oh it is a handler for int messages" and accepts it.... not realizing that it also requires a hidden this argument to be passed to it.
If you try to use it, you'll get a random result/crash if it tries to access any class members because the this pointer is not actually passed to the function, so it accesses random garbage,
So while I'd say this is a bug... I'm not sure were the bug is. std.concurrency can't tell the difference between a REAL void function(int) and this fake one since the address-of operator doesn't forward information about the hidden this pointer. I think that's the real bug.

Related

How to make a local extension method avaiable in a function with receiver?

I found an interesting thing, but I couldn't do it. Is there any way to make the local extension method available in a function with receiver.
val list = ArrayList<Any>();
fun <T> Array<T>.bind(context: MutableList<in T>, block: Array<T>.() -> Unit) {
fun Array<T>.save() {
context.addAll(this);
}
block();
}
arrayOf(1, 2, 3).bind(list) {
save(); //todo: how to bind extension in execution scope
};
I know there is an alternative way by introducing another type for the receiver, but I want to avoid it. for example:
interface Savable {
fun save();
}
fun <T> Array<T>.bind(context: MutableList<in T>, block: Savable.() -> Unit) {
val proxy = object : Savable {
override fun save() {
context += this#bind;
}
};
proxy.block();
}
There is no such feature yet, and I think in near future it won't be added either. You should just use your second version. Don't care about adding an wrapper class. The idea of avoiding introducing a wrapper class is actually, as long as you are using JVM backend, just nonsense, because by using local function you are actually adding a local class.
This is the equivalent Java code of your kotlin function, after fixing as you have suggested, with the assumption that your bind function lives in file bind.kt:
public final class BindKt {
public static <T> void bind(T[] receiver, List<? super T> context, Function1<T> block) {
class Local { // the name of local class is unimportant, as it's generated by compiler. It should looks like "package.name.BindKt$bind$X" where X is a number.
public void save(T[] receiver) {
context.addAll(receiver);
}
}
block.invoke(this); // this won't compile. Neither will yours.
}
}
As you can see save is NOT compiled to a static method, which means, if your block somehow ever called that save, an instance of Local must be fist created. So, no matter what you do, as long as you used a local function, there is basically no point in avoiding introduing a wrapper class. Your second solution is good, and just use it. It's both elegant and efficient enough.
If you really don't want add a class/object creation, move these extension functions to a package scope, and let clients import them.

QtConcurrent::map() with member function = can not compile

My project is to create a small program which demonstrates the work of a search engine: indexing and returning result for arbitrary queries. I've done the work with the indexer part and now I want to improve it with indexing multiple files at once. The MainWindow class is here:
class MainWindow : public QMainWindow
{
Q_OBJECT
.....
private:
Indexer * indexer;
QStringList fileList;
....
void index(QStringList list);
void add(const QString &filename);
}
This is the implementation of add (add need to access fileList to avoid index the same files again, thus it can not be static method):
void MainWindow::add(const QString &filename)
{
if (!fileList.contains(filename))
{
indexer->addDocument(filename.toStdString());
fileList.append(filename);
qDebug() << "Indexed" << filename;
emit updatedList(fileList);
}
}
The implement of index method is to receive a file lists and call add upon each file name:
void MainWindow::index(QStringList list)
{
....
QtConcurrent::map(list, &MainWindow::add);
....
}
The error I receive when compiling these code is:
usr/include/qt4/QtCore/qtconcurrentmapkernel.h: In member function 'bool QtConcurrent::MapKernel<Iterator, MapFunctor>::runIteration(Iterator, int, void*) [with Iterator = QList<QString>::iterator, MapFunctor = QtConcurrent::MemberFunctionWrapper1<void, MainWindow, const QString&>]':
../search-engine/mainwindow.cpp:361:1: instantiated from here
/usr/include/qt4/QtCore/qtconcurrentmapkernel.h:73:9: error: no match for call to '(QtConcurrent::MemberFunctionWrapper1<void, MainWindow, const QString&>) (QString&)'
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:128:7: note: candidate is:
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:138:14: note: T QtConcurrent::MemberFunctionWrapper1<T, C, U>::operator()(C&, U) [with T = void, C = MainWindow, U = const QString&]
/usr/include/qt4/QtCore/qtconcurrentfunctionwrappers.h:138:14: note: candidate expects 2 arguments, 1 provided
I'm not really familiar with how QtConcurrent works, and the documentation doesn't provide much details about it. I really hope that someone here can help. Thanks in advance.
To be able to call a pointer-to-member, you need, in addition to that functions formal arguments, an instance of that class (the this pointer that you get inside member functions).
There are two ways to handle this: create a simple functor to wrap the call, or use a lambda.
The functor would look like this:
struct AddWrapper {
MainWindow *instance;
AddWrapper(MainWindow *w): instance(w) {}
void operator()(QString const& data) {
instance->add(data);
}
};
And you'd use it like:
AddWrapper wrap(this);
QtConcurrent::map(list, wrap);
(Careful with the lifetime of that wrapper though. You could make that more generic - you could also store a pointer-to-member in the wrapper for instance, and/or make it a template if you want to reuse that structure for other types.)
If you have a C++11 compiler with lambdas, you can avoid all that boilerpalte:
QtConcurrent::map(list, [this] (QString const& data) { add(data); });
Note: I'm not sure how QtConcurrent::MemberFunctionWrapper1 got involved in your example, I'm not seeing it here. So there might be a generic wrapper already in Qt for this situation, but I'm not aware of it.

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.

C# Func(T) not accepting ref type input parameter

Can Func<...> accept arguments passed by reference in C#?
static void Main()
{
Func<string,int, int> method = Work;
method.BeginInvoke("test",0, Done, method);
// ...
//
}
static int Work(ref string s,int a) { return s.Length; }
static void Done(IAsyncResult cookie)
{
var target = (Func<string, int>)cookie.AsyncState;
int result = target.EndInvoke(cookie);
Console.WriteLine("String length is: " + result);
}
I am not able define a Func<...> which can accept the ref input parameter.
The Func<T> delegates cannot take ref parameters.
You need to create your own delegate type which takes ref parameters.
However, you shouldn't be using ref here in the first place.
Expanding on SLaks answers.
The Func<T> family of delegates are generic and allow you to customize the type of the arguments and returns. While ref contributes to C#`s type system it's not actually a type at the CLR level: it's a storage location modifier. Hence it's not possible to use a generic instantiation to control whether or not a particular location is ref or not.
If this was possible it would be very easy to produce completely invalid code. Consider the following
T Method<T>() {
T local = ...;
...
return local;
}
Now consider what happens if the developer called Method<ref int>(). It would produce both a local and return value which are ref. This would result in invalid C# code.

Why won't the GC automatically dispose my class's members?

When I build the following C++/CLI code in VS2008, a code analysis warning CA1001 is displayed.
ref class A
{
public:
A() { m_hwnd = new HWND; }
~A() { this->!A(); }
protected:
!A() { delete m_hwnd; }
HWND* m_hwnd;
};
ref class B
{
public:
B() { m_a = gcnew A(); }
protected:
A^ m_a;
};
warning: CA1001 : Microsoft.Design :
Implement IDisposable on 'B' because
it creates members of the following
IDisposable types: 'A'.
To resolve this warning, I would have to add this code to class B:
~B() { delete m_a; }
But I don't understand why. Class A implements IDisposable via its destructor (and finalizer).
So surely whenever A gets garbage-collected, then A's finalizer or destructor will get called, freeing its unmanaged resources.
Why does B have to add a destructor to call 'delete' on its A member?
Will the GC only call A's destructor if B explicitly calls "delete m_a"?
Edit: it seems this works automatically if you use the "syntax sugar" method of declaring the A member, like this:
ref class B
{
public:
B() { }
protected:
A m_a;
};
but this is not always possible.
Why isn't the GC clever enough to automatically dispose of the managed reference pointer of A^, once no one else has a pointer to it?
You should use stack semantics for the member and add a destructor to the containing class.
Then the member will be disposed.
See http://msdn.microsoft.com/en-us/library/ms177197.aspx
ref class B
{
public:
B() {}
~B() {}
protected:
A m_a;
};
The member is still a ref. type and is still created on the heap.
Edit:
Dispose in .net is at best unfortunate, in C# the whole deterministic behaviour is broken and you have to be really rigerous with Dispose calls to get the behaviour most c++ developers expect.
In c++/cli stack semantics make it better. If you can't use them you are back to having to explicitly call dispose which in c++/cli is represented by the destructor.
The only way to automatically chain dispose calls to members is through stack semantics if the members are normal managed pointers just like c# you'll have to chain the calls manually.
Many classes could hold the same A^ pointer, there is no way to know which one should call the destructor.
You get the warning because you have implemented the destructor which causes your class to implement IDispose. This gives you a chance to clean up in a deterministic manner.
The GC alone can only collect an object with no references and call the finalizer. This is far from deterministic. Note that relying on the finalizer to do the clean up should be a safety net only as it may be called a long time in the future if at all.
I would recommend trying to design your code to allow the above pattern.

Resources