c语言多线程队列读写
最近用c语言写了个简单的队列服务,记录一下,文件结构为 main.c queue.c queue.h,代码如下:
主函数
#define NUM_THREADS 200 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <queue.h> #include <pthread.h> #include <sys/time.h> #include <unistd.h> struct threadArgs { struct queue *q; char *c ; }; void* putArg(void *params) { struct threadArgs *args = params; putQueue(args->q, args->c); } int main() { pthread_t tids[NUM_THREADS]; //线程id struct queue * g_q; g_q = initQueue(); char c[LENTH] = "test\0"; char b[LENTH] = "btest\0"; char a[LENTH] = "atest\0"; char *h = ""; int i = 0; for( i = 0; i < NUM_THREADS; ++i ) { struct threadArgs *args; args = (struct threadArgs *)malloc(sizeof(struct threadArgs)); 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 , sleep for a while"); sleep(3); } else { sleep(1); } } return 0; }
queue.h
#define LENTH 10240 struct node { char * m_content; struct node * p_next; }; struct queue { struct node * p_head; struct node * p_tail; }; struct queue * initQueue(); void putQueue(struct queue *q, char content[LENTH]); char * getQueue(struct queue *q); struct node * initNode();
queue.c
#include <stdio.h> #include <string.h> #include <queue.h> #include <stdlib.h> struct node * initNode(char c[LENTH]){ struct node *h; h=(struct node *)malloc(sizeof(struct node)); 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; return h; } struct queue * initQueue() { struct queue * q; q=(struct queue *)malloc(sizeof(struct queue)); if (q == NULL) { printf("can not malloc struct node memory;"); exit(1); } q->p_head = NULL; q->p_tail = NULL; return q; }; void putQueue(struct queue *q, char c[LENTH]) { struct node * n; n = initNode(c); if (q->p_tail == NULL) { // queue is empty q->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(struct queue *q) { char *c; if (q->p_head==NULL) { c = "0"; return c; } struct node * h; h = q->p_head; c = h->m_content; printf("get: %s\n", c); q->p_head = q->p_head->p_next; free(h); //这里不能c指针 回收以后c指针的返回值 会出问题 return c; } //几点收获 指针需要malloc 普通变量不需要, 特别是字符串数组不需要
编译 gcc -o q main.c queue.c -I ./ -lpthread