Sharing data between threads

Sharing data between threads

Post by Jasper Spi » Sun, 30 Apr 2000 04:00:00



Hi,

Situation : main process spawns thread 1 for each connection. Thread 1
in turn spawns thread 2 (pthread_create).
I need to share data between thread 1 and thread 2.

I tried doing this by using a static variable in thread 1 and thread 2.
This
works OK, but all other client connections then use the same value for
the
variable. I thought the scope of a static variable was from parent
process
to client process ?

Is there a way to fix this or should I use shared memory (shmat &
shmctl) ?

Thanks,

Jasper

 
 
 

Sharing data between threads

Post by Patrick TJ McPh » Sun, 30 Apr 2000 04:00:00




% I need to share data between thread 1 and thread 2.
%
% I tried doing this by using a static variable in thread 1 and thread 2.
% This
% works OK, but all other client connections then use the same value for
% the
% variable. I thought the scope of a static variable was from parent
% process
% to client process ?

Static variables are not shared between processes, and threads are not
processes, anyway. Also, posix doesn't have the concept of parent and
child relationships between threads.

Threads share all the resources of a process. In particular, every
memory address within a process's address space is available to all
threads in the process, so there are lots of ways to share memory
between two threads. For instance, you can use

global variable:
 the problem here is that the global variable address will be the same for
 every thread in the system. You can get around this by making an array
 and working out a scheme of allocating array indices. Ie, for connection
 1, you use array index 0, for connection 2, you use index 1, etc.

static variable, with address passed in pthread_create call:
 this is exactly like a global variable, except the scope of the
 variable name is limited either to a function or a compilation unit.

dynamic allocation (malloc/new/mmap):
 allocate a chunk of memory in thread A and pass its address to thread
 B. You have to be very careful that both threads are finished with it
 before you free it.

auto variable:
 don't do this, because you'll probably have a problem and then everyone
 will blame me for suggesting it, but you can pass the address of a local
 variable from the thread function of thread A, and use it in both threads.
 You _must_ ensure that thread B finishes before thread A (ie, using
 pthread_join) or your program will crash.

shared memory:
 don't do this, because it's ridiculous, but you could allocate shared
 memory using shmat or mmap and treat it as if it had been allocated
 using malloc.

In any case, make sure you use mutexes and/or condition variables to
control access to the shared data.
--

Patrick TJ McPhee
East York  Canada