[erlang-questions] Port Driver. erl_drv_thread_join and ErlDrvTid reuse.

Zhemzhitsky Sergey Sergey_Zhemzhitsky@REDACTED
Tue Oct 2 15:55:58 CEST 2012


Hello erlang gurus,

Currently I’ve faced with the following issue with termination of threads created in port drivers.

I’m creating a separate thread in the erlang port driver that sends terms to some erlang process.

--------------------------------------
The thread is created like this:

ErlDrvTid threadId;
if(erl_drv_thread_create(“thread name”, &threadId, threadFunc, threadData, NULL)) {
    // log error & exit
}
driverData->tid = threadId;

Driver data looks like this:
struct DriverData {
    ErlDrvPort port;
    ErlDrvTid tid;
    int isRunning;
}
--------------------------------------

Thread function looks like this
DriverData* data = (DriverData*) threadData
data. isRunning = 1;
while(data.isRunning) {
    doSomething();
}
--------------------------------------

When I’d like to stop this thread from one of the driver callbacks I do something like this:

void handleInput(ErlDrvData handle, char * buf, ErlDrvSizeT len) {
    DriverData* data = (DriverData*) handle;

    int command = parseBuf(buf, len);
    if (command == STOP) {
        data.isRunning = 0;
        if(erl_drv_thread_join(data->tid, NULL)) { // here is the place where EDEADLK happens
            // report error
        }
    } else {
        …
    }
}

>From time to time erl_drv_thread_join returns error EDEADLK=35, i.e. the current thread (scheduler thread) tries to join itself.

According to the documentation “A Thread identifier may be reused very quickly after a thread has terminated. Therefore, if a thread corresponding to one of the involved thread identifiers has terminated since the thread identifier was saved, the result of erl_drv_equal_tids() might not give the expected result.”

I suppose that thread terminates earlier then erl_drv_thread_join call happens, so ErlDrvTid is already reused.

So the question is how to use erl_drv_thread_join properly and how to guarantee that the saved ErlDrvTid value points to the same data that was returned from erl_drv_thread_create?

Best Regards,
Sergey


_______________________________________________________
CONFIDENTIALITY NOTICE: This email and any files attached to it may be conf idential. If you are not the intended recipient you are notified that using, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited. If you have received this email in error please notify the sender and delete this email. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20121002/f3671708/attachment.htm>


More information about the erlang-questions mailing list