user1047069
user1047069

Reputation: 953

Local static variable and multithreading — is it safe?

If I have

pthread_create(newThread, &attr, threadFunc, arg)

which is called several times to create threads that run threadFunc, and threadFunc is something like:

void threadFunc(){      static int x = 0;      }

Is this x variable shared between all threads? I know it's not in the thread's stack, because it's static, and it sits where global variables are. If not, and each thread has it's own x, there's no need for locks — is that right?

Upvotes: 1

Views: 625

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

That static x is shared by all threads that use threadFunc as its start routine. If you want each thread has a copy of that x, you should use thread-specific data.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234705

No it is not thread-safe and x is shared between all the threads. Furthermore, operations on an int in C are not guaranteed to be atomic.

Upvotes: 4

Related Questions