Recently wrote a simple queue service in C language, record, the file structure is MAIN.C queue.c queue.h, the code is as follows:
Main function
#defineNum_threads 200#include<stdio.h>#include<stdlib.h>#include<string.h>#include<queue.h>#include<pthread.h>#include<sys/time.h>#include<unistd.h>structthreadargs{structQueue *Q; Char*c;};void* PUTARG (void*params){ structThreadargs *args =params; Putqueue (args->q, args->c);}intMain () {pthread_t tids[num_threads];//Thread ID structQueue *g_q; G_q=Initqueue (); CharC[lenth] ="Test\0"; CharB[lenth] ="Btest\0"; CharA[lenth] ="Atest\0"; Char*h =""; inti =0; for(i =0; i < num_threads; ++i) {structThreadargs *args; Args= (structThreadargs *) malloc (sizeof(structThreadargs)); Args->q =g_q; Args->c =C; Pthread_create (&Tids[i], NULL, Putarg, args); } while(1) {h=Getqueue (G_Q); printf ("%s\n", h); if(strcmp (H,"0") ==0) {printf ("queue is empty and sleep for a while"); Sleep (3); } Else{sleep (1); } } return 0;}
Queue.h
#defineLenth 10240structnode{Char*m_content; structNode *P_next;};structqueue{structNode *P_head; structNode *P_tail;};structQueue *initqueue ();voidPutqueue (structQueue *q,CharContent[lenth]);Char* Getqueue (structQueue *q);structNode * Initnode ();
Queue.c
#include <stdio.h>#include<string.h>#include<queue.h>#include<stdlib.h>structNode * Initnode (CharC[lenth]) { structNode *h; H=(structNode *) malloc (sizeof(structnode)); if(h==NULL) {printf ("can not malloc struct node memory;"); Exit (1); } h->m_content = (Char*) malloc (sizeof(Char)*lenth); strcpy (H-m_content, C); printf ("init success \ n"); H->p_next =NULL; returnh;}structQueue *Initqueue () {structQueue *Q; Q=(structQueue *) malloc (sizeof(structqueue)); if(q = =NULL) {printf ("can not malloc struct node memory;"); Exit (1); } q->p_head =NULL; Q->p_tail =NULL; returnq;};voidPutqueue (structQueue *q,CharC[lenth]) { structNode *N; N=Initnode (c); if(Q->p_tail = = NULL) {//queue is emptyQ->p_head =N; Q->p_tail =N; } Else{Q->p_tail->p_next =N; Q->p_tail =N; } printf ("put:%s\n", q->p_tail->m_content);}Char* Getqueue (structQueue *q) {Char*C; if(q->p_head==NULL) {C="0"; returnC; } structNode *h; H= q->P_head; C= h->m_content; printf ("Get:%s\n", c); Q->p_head = q->p_head->P_next; Free (h); //The return value of the C pointer will be problematic after recycling here returnC;}//a few harvesting pointers are required for malloc normal variables, especially if the string array does not need
C language Multi-threaded queue reading and writing