toastedDeli
toastedDeli

Reputation: 580

Calling a function from inside a pthread?

If I have a threaded function, and from inside it I call another function (that is located in a separate .c file), does each instance of the threaded function get it's own version of the called function? Example:

file 1

void* threaded_func(void* data) {
  function2(...);
}

file 2

int a;

int function2(...) {
  int b;
}

In my example, would int a be the same int a for all threads? What about for variables I define inside function2 (i.e int b)?

Some context:

I'm creating a simple HTTP server and my function2 is a serve_client function which should only return when the connection is closed. I'm having a problem that I think is due to some variables in file2 (int a) being overwritten for each new thread. I think my problem is me expecting a C source file to behave like a class would in Java.

Upvotes: 0

Views: 3939

Answers (2)

A C function is just machine code, and could be run by several threads (or processes). What matters is the data used by that function. C don't have closures (you could emulate them with callbacks, that is some function using additional client data). As answered by usr read also about thread local storage duration with thread_local. Each thread has its own call stack.

You should first read some POSIX thread tutorial.

You need to care about synchronization (and semaphores), notably using mutexes (and lock so serialize access to global shared variables). Read also about ACID transactions. Sometimes you can use atomic types and atomic operations.

BTW, you might want to use some HTTP server library like libonion.

You should look into the source code of existing free software projects (e.g. on github).

On Linux, read also about pthreads(7), nptl(7) and futex(7) and sem_overview(7) and clone(2).

Upvotes: 2

P.P
P.P

Reputation: 121347

does each instance of the threaded function get it's own version of the called function?

Loosely speaking, that's correct, provided the function doesn't use any global variables (e.g., int a; in your example) or any variable with static storage duration. If a is "shared" by multiple threads, that's likely to the source of your problem.

If a needs to be shared among threads, then you need to synchronize its access. If you a needs to be unique to each of threads, you need thread local storage. E.g., using C11's __Thread_local or gcc's __thread.

Upvotes: 3

Related Questions