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 *)’
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: