01 struct queue_t {

03    node_t *tail;

05 };

01 typedef struct node_t {

02    TYPE value;

03    node_t *next

04 } NODE;

05

06 typedef struct queue_t {

08    NODE *tail;

09    LOCK q_h_lock;

10    LOCK q_t_lock;

11 } Q;

12

13 initialize(Q *q) {

14   node = new_node()   // Allocate a free node

15   node->next = NULL   // Make it the only node in the linked list

16   q->head = q->tail = node   // Both head and tail point to it

17   q->q_h_lock = q->q_t_lock = FREE   // Locks are initially free

18

19

20 enqueue(Q *q, TYPE value) {

21   node = new_node()       // Allocate a new node from the free list

22   node->value = value     // Copy enqueued value into node

23   node->next = NULL       // Set next pointer of node to NULL

24   lock(&q->q_t_lock)      // Acquire t_lock in order to access Tail

25      q->tail->next = node // Link node at the end of the queue

26      q->tail = node       // Swing Tail to node

27   unlock(&q->q_t_lock)    // Release t_lock

28 ｝

29

30 dequeue(Q *q, TYPE *pvalue) {

31   lock(&q->q_h_lock)   // Acquire h_lock in order to access Head

34      if new_head == NULL         // Is queue empty?

35         unlock(&q->q_h_lock)     // Release h_lock before return

36         return FALSE             // Queue was empty

37      endif

40   unlock(&q->q_h_lock)   // Release h_lock

41   free(node)             // Free node

42   return TRUE            // Queue was not empty, dequeue succeeded

43 }

Update: 多线程队列算法有很多种，大家应根据不同的应用场合选取最优算法（例如是CPU密集型还是IO密集型）。本文所列的算法应用在这样一个多线程程序中：每个线程都拥有一个队列，每个队列可能被本线程进行dequeue操作，也可以被其他线程进行dequeue（即work stealing），线程数不超过CPU核心数，是一个典型的CPU/MEM密集型客户端单写者多读者场景。