简体   繁体   中英

Dynamically create sembuf structure in C

I have written a fairly simple program that finds the first N prime numbers (N provided as command line argument) by employing processes. Shared memory segments are used for the array of verified prime numbers, for the current candidate number being considered, and for the number of results obtained thus far (to compare against N to determine when to stop). Semaphores are used to avoid problems with multiple processes accessing the 3 shared memory segments.

I have implemented this same program recently using threads and mutexes, and it was much less trouble. With this in mind, I know my prime number algorithm works. In fact, the current program using processes and semaphores works for the most part.

However, an optional command line argument can be provided to specify the number of processes to use. This was straight forward in the threads version of the program. This time around, however, I have a global sembuf struct with up and down arrays with elements equal to the number of processes being used. Right now I have them both set statically to 3 (the default) and the program works as expected; however, I cannot figure out how to dynamically create these sembufs with different numbers of up and down array element sizes to account for different process numbers (seeing as the struct is global).

I understand how to use malloc to dynamically assign array sizes (as outlined here: Set array size at runtime ), but that they are part of a struct seems to be an issue. Here is my simple sembuf (if that is useful):

// Sembuf struct for semaphore information.
struct sembuf down[SLAVES], up[SLAVES];

where SLAVES is the number of spawned processes coordinating prime number investigation. It works at the default of 3 (or any other value I manually define SLAVES to) currently, but dynamically setting these values is my goal.

Any ideas on how to do this, or a different strategy to achieve a similar outcome, would be much appreciated.

You currently have sth like this, right?

struct Whatever
{
    ...
    struct sembuf down[SLAVES], up[SLAVES];
    ...
};

You should convert that to:

struct Whatever
{
    ...
    size_t slaves;
    struct sembuf *down, *up;
    ...
};

Then you initialize that with malloc():

Whatever whatever;
whatever.slaves = 100;
whatever.down = malloc(sizeof(struct sembuf) * whatever.slaves);
whatever.up = malloc(sizeof(struct sembuf) * whatever.slaves);

It can be used exactly the same way as you used it so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM