Domanda

I'm tasked with writing a producer/consumer program where there are multiple consumers with each consumer corresponding to its own shared data struct, while the producer has access to all the shared data structs. Anyway, the problem I'm running into is initializing each consumer thread with its own struct; this is accomplished via each thread getting its own, unique number. IE, Thread 0 gets number 0 passed in as an argument, thread 1 gets number 1, etc. However, I can only get each thread to get its unique number with a call to sleep.

struct SharedData {
    int         isopen;
    int     refcount;   // reference count:  number of threads using this object
    unsigned int    front;      // subscript of front of queue
    unsigned int    count;      // number of chars in queue
    unsigned int    bufsize;
    pthread_cond_t buffer_full;
    pthread_cond_t buffer_empty;
    pthread_mutex_t mtex;
    fifo_t* queue;
    sem_t       empty_count;

    sem_t       full_count;
    sem_t       use_queue;  // mutual exclusion
};

struct OverSharedData{
    struct SharedData ** rep;
    int rop;
};

int main(int argc, const char *argv[])
//Other Code
struct OverSharedData* remp = (struct OverSharedData*)malloc(sizeof(struct   OverSharedData));
rennit(remp);
struct SharedData * d = *(remp->rep + 0);

//Other Code
for (z=0; z<consumerthreads; z++) {
    remp->rop = z;

    pthread_create((Consumer_Threads+z), 0, Consumer, remp);
    usleep(100);

}

remp->rop is the differing argument for each thread that contains its specific number. If I comment out the usleep like so

 for (z=0; z<consumerthreads; z++) {
    remp->rop = z;

    pthread_create((Consumer_Threads+z), 0, Consumer, remp);

 }

I get this: Entered Consumer: 2

Entered Consumer: 2

Entered Consumer: 2

When I want: Entered Consumer: 0 Entered Consumer: 1 Entered Consumer: 2

The consumer code is here:

 void* Consumer(void *arg){
     pthread_mutex_lock(&grill);
    struct OverSharedData * de = (struct OverSharedData *)arg;
    printf("Entered Consumer: %d\n", de->rop);

    int numb = de->rop;
    pthread_mutex_unlock(&grill);
 //Rest of code not necessary

How do I initialize these threads without using a sleep call

È stato utile?

Soluzione

If your struct is global, it will get updated before Z threads are created. IE. The variable remp->rop will be incremented Z times before the first thread is even executing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top