Monday, November 7, 2011

Vala compile error: cannot infer generic type argument for type parameter `GLib.Thread.create.T'

Today I tried to work with Vala and threads.
Turned out that documentation, even the official sources, is still sketchy and young.
E.g. I tried to build the following, taken from here:
void* thread_func()
{
    stdout.printf("Thread running.\n");
    return null;
}

int main(string[] args)
{
    if (!Thread.supported())
    {
        stderr.printf("Cannot run without threads.\n");
        return 1;
    }

    try
    {
        Thread.create(thread_func, false);
    }
    catch (ThreadError exc)
    {
        return 1;
    }  

    return 0;
}
It will give up compiling with the following error:
$ valac --thread main.vala
 main.vala:19.9-19.21: error:
 cannot infer generic type argument
  for type parameter `GLib.Thread.create.T'
        Thread.create(thread_func, false);
        ^^^^^^^^^^^^^
 Compilation failed: 1 error(s), 0 warning(s) 
The compiler does complain about an actual lack in my code. Infact the declaration of "Thread.create()" is:
Thread<T> create<T>(ThreadFunc<T> func, bool joinable)
The culprit is the generic type "T" to be passed to the create method.

But the type of what I need to provide?
Thread.create<?>(thread_func, false)
It's the return type of the thread function "thread_func" passed as the first parameter to the create method.
Hence I need to call it this way instead:
Thread.create<void*>(thread_func, false)
In the case thread_func had returned bool:
Thread.create<bool>(thread_func, false)
And so on.

Here's the incomplete documentation for the create method that led me to the initial impasse.
Here is where I found the solution (thanks to Abderrahim Kitouni) instead.
Yeah, a bit of Googling helped me as well.