PDA

View Full Version : Sharing a C struct



rotis23
02-21-2004, 07:58 AM
Hi All,

I've got a problem.

I have wrapped a C linux library using perl-xs. The library provides

- an init function (where a C struct is initialised)
- a do function (where actions are performed using the C struct)
- a free function (where the C struct is freed).

I have 30 perl slaves (processes) that each use their own instance of the C struct in memory.

The problem is that each struct requires around 30 MB (30 *30 = a lot).

Now I would normally initialise the struct in the parent perl controlling thread and pass it too each slave, however I do not have control of the parent thread (at least not withour hacking someone else's source code).

So, the question is, how can I share the initialised C struct between all threads? I've had a couple of ideas:

- write a server that maintains a pointer to the struct.
- keep the struct in a file :/ ?!
- somehow cache the struct between processes within the C side of the wrapper - how could I do this?

Any ideas?

Thanks for any help on this,

rotis23

CornedBee
02-21-2004, 04:51 PM
I think the third approach is not feasible. The second is slow, depending on the way you use the file. If you can memory map a file on a RAM disk, it would be quite ok, but a hard disk is slow. The first sounds the best, but it's hard work, you need to implement the server and provide some protocol for communication, locking etc. The advantage is that you can make it a distributed app very easily :)

rotis23
02-22-2004, 11:40 AM
Thanks for your reply CornedBee.

I've found a chapter in my Linux programming book that describe 'Shared Memory'.

Can I use this to solve my problem?

I assume this is going to raise all sorts of locking issues.

CornedBee
02-22-2004, 03:47 PM
Should be possible. But write sync is gonna be a nightmare :)

There should be cross-process mutexes too, though. The front page of the Linux forum even contains a thread that mentions mutex, but I didn't look at it.