线程调用C中的入队函数

时间:2011-05-24 05:37:17

标签: c multithreading queue

我有:

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++;
}

可以打电话:

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

和一些线程创建如:

   #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);
  }

我应该如何在每个线程调用的pthread_create中修改enqueue函数

enqueue( variable, &Q);  

(我正在做一个无锁队列,并且已经有了逻辑,但我陷入困境中每个线程如何调用入队函数...)

- 编辑 -

我正在提出答案并获得:

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

1 个答案:

答案 0 :(得分:3)

有一个例子,没有任何错误检查等。另外,如果您使用线程,您应该使用互斥锁来防止同时访问您的队列(或使用一些无锁算法)。 只需添加下一个更改:

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;
}