K-RAN
K-RAN

Reputation: 893

How does pthread_create() work?

Given the following:

pthread_t thread;
pthread_create(&thread, NULL, function, NULL);

Upvotes: 11

Views: 6628

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279255

What exactly does pthread_create do to thread?

thread is an object, it can hold a value to identify a thread. If pthread_create succeeds, it fills in a value that identifies the newly-created thread. If it fails, then the value of thread after the call is undefined. (reference: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html)

What happens to thread after it has joined the main thread and terminated?

Nothing happens to the object, but the value it holds no longer refers to any thread (so for example you can no longer pass it to functions that take a pthread_t, and if you accidentally do then you might get ESRCH errors back).

What happens if, after thread has joined, you do this:

Same as before: if pthread_create succeeds, a value is assigned that identifies the newly-created thread.

Upvotes: 5

Paul Rubel
Paul Rubel

Reputation: 27222

pthread_create will create a thread using OS calls. The wonderful things about abstraction is that you don't really need to care what's happening below. It will set the variable thread equal to an identifier that can be used to reference that thread. For example, if you have multiple threads and want to cancel one of them just call

pthread_cancel(thread)

using the right pthread_t identifier to specify the thread you're interested in.

What happens to thread after it has joined the main thread and terminated?

Before the thread terminates the var thread serves as a key/index to get at or identify a thread. After the thread terminates the value that the key/index pointed to no longer has to be valid. You could keep it around and try to reuse it, but that's almost certain to cause errors.

What happens if, after thread has joined, you do this:

pthread_create(&thread, NULL, another_function, NULL);

No problem, since you give it a reference to thread the value of thread will be set to an identifier for the new thread that was just made. I suspect its possible that it could be the same as before, but I wouldn't count on it.

Upvotes: 2

Related Questions