How to create multiple threads using QtConcurrent::run()



  • I tried running QtConcurrent::run() in a loop, but program crashes:

    @void Scanner::scan()
    {
    for(int i=0;i<ipList.length();i++)
    {
    QtConcurrent::run(this,&Scanner::scanThread,i);
    }

    }@



  • Hi,

    this code does not say much.
    How does it crash? DId you check the call stack for the crash?



  • Here is the error:

    @talloc: access after free error - first free may be at ../lib/util/talloc_stack.c:103
    Bad talloc magic value - access after free
    The program has unexpectedly finished.@



  • @void Scanner::scan() // using libsmbclient library
    {
    for(int i=0;i<ipList.length();i++)
    {
    QtConcurrent::run(this,&Scanner::scanThread,i);
    }
    }
    void Scanner::scanThread(int i)
    {
    int dh;
    QString ip;
    ip="smb://"+ipList[i]+"/";
    dh= smbc_opendir(ip.toAscii()); // debugger points to this location
    if(dh<0)
    return;
    emit
    updateTree(i,dh); // on commenting this line, it still crashes
    }
    @



  • @smbc_opendir(ip.toAscii());@
    is a blocking function call. using mutex around the function, prevents the crash, but forces serialization, defeating the purpose of multi-threading, as only one thread runs at a time. Is there any way out!



  • Are you sure that smbc_opendir() is thread safe (I doubt)? If not, you will have to serialize the access or use multiple processes.



  • The library is not thread safe. I tried this:
    @void ShareScanner::scanThread(int i)
    {
    int dh;
    QString ip;

    ip="smb://"+ipList[i]+"/";
    mutex.lock();
    dh= smbc_opendir(ip.toAscii());
    mutex.unlock();
    if(dh<0)
        return;
    updateTree(i,dh);
    

    }@

    It works fine, but only one thread executes at a time. Can you plz explain what you mean by multiple processes. I suppose QProcess is for IPC only!



  • If the library isn't thread safe you can't use it in multiple threads in a single process (at least not concurrently), but you can use it concurrently in different processes, as they all have their instance of the library.

    You will have to spawn multiple processes using QProcess, each process scanning a given share and communicating the information gathered back to the application (using some kind of IPC, like stdout, shared memory or sockets).

    Be aware that spawing processes doesn't come for free as well, so it might be useful to spawn a bunch of process which then are reused to scan different shares consecutively. But this is up to a performance analysis.

    And keep in mind that models aren't thread safe out of the box as well.



  • How can i run a function using QProcess, is it possible



  • You have to create a new process, which means you have to code it, e.g. a console application. Then you can spawn the exectutable with QProcess.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.