Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gettid() returning the same value for two different threads?

I have a program written by my professor (I modified it a bit to test stuff). From what I understand, on a Linux system:

  1. user threads cannot take advantage of a multicore system while kernel threads can. Since pthread can take advantage of a multicore system, it's a kernel thread

  2. gettid returns the id assigned by the kernel and should be unique since the threads run on different cores; pth_self returns the id within the process

I expected to see 2 different values for gettid, but this is what I got:

Code:

void *count(void *arg) {
    printf("pth_self : %d gettid() : %i \n", pth_self(), gettid());
}

int main(int argc, char **argv) {
    pth_init();
    pth_t t1, t2;
    t1 = pth_spawn(PTH_ATTR_DEFAULT, count, &a);
    t2 = pth_spawn(PTH_ATTR_DEFAULT, count, &a);
    pth_join(t1,NULL);
    pth_join(t2,NULL);
    return 0;
}

output:

pth_self : 23023312 gettid() : 45868 
pth_self : 23090368 gettid() : 45868

Why is gettid returning the same thing for the 2 threads? I also got a warning about some kind of "implicit declaration of gettid" if that's important.

Thanks

like image 560
mystackoverflowaccount Avatar asked Jul 02 '26 00:07

mystackoverflowaccount


1 Answers

You are mixing pthread and pth.

The first use clone and futex system call (see here). The threads are known by the kernel and can take profit of SMP system.

The second does all in user space: The kernel see only one thread, so gettid() will return the same value in all 'thread'.

You may ask "Why pth exists if it doesn't create real threads?"

The answer is here:

Pth increases the responsiveness and concurrency of an event-driven application, but NOT the concurrency of number-crunching applications.


To have different tid values for different thread, you'll have to change your code to:

/* compile with -pthread */
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <pthread.h>

/* see NOTES of https://linux.die.net/man/2/gettid for explanation */
#define gettid() syscall(SYS_gettid)

void *count(void *arg) {
    printf("pthread_self : %ld gettid() : %li \n", pthread_self(), gettid());
    return NULL;
}

int main(int argc, char **argv) {
    pthread_t t1, t2;

    pthread_create(&t1, NULL, count, NULL);
    pthread_create(&t2, NULL, count, NULL);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    return 0;
}

Output:

pth_self : 140492392244992 gettid() : 4422 
pth_self : 140492383852288 gettid() : 4423 

Try it online

like image 183
Mathieu Avatar answered Jul 04 '26 13:07

Mathieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!