fengqi
fengqi

Reputation: 377

How does pthread_self() always succeed?

When I was learning pthread, the manual says pthread_self() always succeeds.

ERRORS

This function always succeeds.

How does that happen? How do we determine whether a function will always succeed?

I tried to find the answer from the code, and I encounter the following code:

# define THREAD_SELF \
  ({ struct pthread *__self;                                      \
     asm ("movl %%gs:%c1,%0" : "=r" (__self)                      \
      : "i" (offsetof (struct pthread, header.self)));            \
     __self;})

I didn't see the field header.self in struct pthread, did I look into the wrong definition? And what does the %c1 mean? Is the input i unused?

Upvotes: 2

Views: 139

Answers (1)

Andrew Henle
Andrew Henle

Reputation: 1

pthread_self() returns the identifier of the currently-running thread. It has to be called by the "currently running thread", so that identifier must exist.

How can that fail? It's the same way that we all assume that expressions such as x++; or y = x / z can't fail.

Upvotes: 1

Related Questions