edgarmtze
edgarmtze

Reputation: 25048

Thread calling enqueue function in C

I have:

struct elem {                  
   data          d;
   struct elem   *next;
};

typedef   struct elem   elem;

struct queue {
   int    cnt;                  
   elem   *front;              
   elem   *rear;               
};

void enqueue(data d, queue *q);

void enqueue(data d, queue *q)
{
   elem   *p;
   p = malloc(sizeof(elem));
   p -> d = d;
   p -> next = NULL;
   if (!empty(q)) {
      q -> rear -> next = p;
      q -> rear = p;
   }
   else
      q -> front = q -> rear = p;
   q -> cnt++;
}

which would be call:

int main(){
   struct queue Q;
   initialize(&Q); //init the queue
   enqueue( 10000, &Q);  
return 0;
}

and some thread creation like:

   #include <pthread.h>
   #include <stdio.h>
   #include <stdlib.h>
   #define NUM_THREADS 5
   /**
    * 
    *
    */
  pthread_t threads[NUM_THREADS];
  long t;
  for(t=0;t<NUM_THREADS;t++){
      pthread_create(&threads[t], NULL, enqueue, (void *)t);
  }

How should I modify the enqueue function so in the pthread_create each thread call

enqueue( variable, &Q);  

(I am doing a lock free queue, and already has the logic, but I am stuck in How would each thread call enqueue function...)

--EDIT--

I am doing the answer proposed and getting:

    queue.c: In function ‘main’:
    queue.c:130: warning: passing argument 3 of ‘pthread_create’
    from incompatible pointer type /usr/include/pthread.h:227: 
    note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(data,  struct queue *)’

Upvotes: 0

Views: 2060

Answers (1)

tvn
tvn

Reputation: 634

There is an example, without any error checking, etc. Also, if you use thread you should use mutex to prevent simultaneous access to your queue (or use some lock free algo). Just add the next changes:

struct thread_data {
    data          d;
    struct queue *q;
};

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct queue Q;

void* thread_func(void* a)
{
    struct thread_data *t = (struct thread_data *)a;

    pthread_mutex_lock(&mutex); // Just example, better use Lock in enqueue
    enqueue(t->d, t->q);
    pthread_mutex_unlock(&mutex);

    free(t);
    return NULL;
}

int main(){
    pthread_t threads[NUM_THREADS];
    long t; // I hope you will initialize it in some proper way

    initialize(&Q); //init the queue
    for(t=0;t<NUM_THREADS;t++){
        struct thread_data *arg = (struct thread_data *) malloc(sizeof(struct thread_data));
        arg->q = &Q;
        arg->d = t; // Actually it is should be your data
        pthread_create(&threads[t], NULL, thread_func, (void *)arg); //FIXED: thread_func is the thread function
    }

    return 0;
}

Upvotes: 3

Related Questions