Posix threads in linux

How does POSIX Threads work in linux?

I thought pthread uses clone to spawn one new thread in linux. But if so, all of the threads should have their seperate pid. Otherwise, if they have the same pid, the global variables in the libc seem to be shared. However, as I ran the following program, I got the same pid but the different address of errno.

extern errno; void* f(void *arg) < printf("%u,%p\n", getpid(), &errno); fflush(stdin); return NULL; >int main(int argc, char **argv)

2 Answers 2

I’m not sure exactly how clone() is used when pthread_create() is called. That said, looking at the clone() man page, it looks like there is a flag called CLONE_THREAD which:

If CLONE_THREAD is set, the child is placed in the same thread group as the calling process. To make the remainder of the discussion of CLONE_THREAD more readable, the term «thread» is used to refer to the processes within a thread group.

Thread groups were a feature added in Linux 2.4 to support the POSIX threads notion of a set of threads that share a single PID. Internally, this shared PID is the so-called thread group identifier (TGID) for the thread group. Since Linux 2.4, calls to getpid(2) return the TGID of the caller.

It then goes on to talk about a gettid() function for getting the unique ID of an individual thread within a process. Modifying your code:

#include #include #include #include #include int errno; void* f(void *arg) < printf("%u,%p, %u\n", getpid(), &errno, syscall(SYS_gettid)); fflush(stdin); return NULL; >int main(int argc, char **argv)

(make sure to use «-lpthread»!) we can see that the individual thread id is indeed unique, while the pid remains the same.

rascher@coltrane:~$ ./a.out 4109,0x804a034, 4109 4109,0x804a034, 4110 

Источник

Читайте также:  Linux установка midnight commander
Оцените статью
Adblock
detector