1

I need to get current perl thread id in a C function inside *.XS part of a perl module.

In pure perl (*.pm part) I would simply do:

$id = threads->tid();

But what is a recommended way to get this value in XS?

Unfortunately http://perldoc.perl.org/perlthrtut.html and http://perldoc.perl.org/threads.html do not talk about dealing with threads in XS.

Thanks in advance

-- kmx

kmx
  • 7,912
  • 1
  • 15
  • 9

2 Answers2

2

To call a method, one uses call_method.

 UV get_tid() {
    dSP;
    UV tid;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    XPUSHs(sv_2mortal(newSVpv("threads", 0)));
    PUTBACK;

    count = call_method("tid", G_SCALAR|G_EVAL);

    SPAGAIN;
    if (SvTRUE(ERRSV) || count != 1)
        tid = 0;
    else
        tid = (UV)POPi;
    PUTBACK;

    FREETMPS;
    LEAVE;

    return tid;
 }
kmx
  • 7,912
  • 1
  • 15
  • 9
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Thanks. This works but only in case when my module is loaded (by "use MyModule") together with "use threads". How to detect in XS that threads were not loaded (thus tid=0)? Now your code thows an error like: Can't locate object method "tid" via package "threads" at ... – kmx Jan 27 '12 at 20:50
  • I have got it, I need G_SCALAR|G_EVAL – kmx Jan 27 '12 at 21:03
  • There should also be a #ifndef USE_ITHREADS tid = 0 and optionally a module importer via Perl_load_module(). – rurban Aug 16 '17 at 15:59
  • Let the .pm handle that. – ikegami Aug 16 '17 at 16:12
0

See how threads itself does it! I suggest you download threads from CPAN, unpack it and take a look at threads.xs. The part you need is a function called ithread_tid.

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • It returns threads' internal variable MY_CXT.context which I am afraid is not directly accessible from other modules – kmx Jan 27 '12 at 20:52