#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<pthread.h>
#define MAXSIZE 1024
typedef struct Queue {
int front;
int rear;
char data[MAXSIZE];
}Queue;
Queue* initQueue() {
Queue* Q = (Queue*)malloc(sizeof(Queue));
Q->front = Q->rear = 0;
return Q;
}
void* thread_push(void* arg);
void* thread_pop(void* arg);
void printQueue(Queue* Q) {
// 队列当前元素个数
int length = (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
int index = Q->front;
for (int i = 0; i < length; i++) {
printf("%s -> ", Q->data[index]);
index = (index + 1) % MAXSIZE;
}
printf("NULL\n");
}
int isFull(Queue* Q) {
if ((Q->rear + 1) % MAXSIZE == Q->front) {
return 1;
}
else {
return 0;
}
}
int isEmpty(Queue* Q) {
if (Q->front == Q->rear) {
return 1;
}
else {
return 0;
}
}
int enQueue(Queue* Q, char data) {
if (isFull(Q)) {
return 0;
}
else {
Q->data[Q->rear] = data;
Q->rear = (Q->rear + 1) % MAXSIZE;
return 1;
}
}
char deQueue(Queue* Q) {
if (isEmpty(Q)) {
return -1;
}
else {
char data = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return data;
}
}
Queue* Q;
int main() {
Q=initQueue();
//创建两个线程
pthread_t id[2];
pthread_create(&id[0], NULL, thread_push, NULL);
pthread_create(&id[1], NULL, thread_pop, NULL);
//等待线程结束
pthread_join(id[0], NULL);
pthread_join(id[1], NULL);
printQueue(Q);
return 0;
}
void* thread_push(void* arg)
{
int i;
while (1)
{
char shuju[10] = { '0','1','0','3','5','4','7','6','9','\0' };
int len = sizeof(shuju) / sizeof(shuju[0]);
printf("len:%d\n", len);
for (int i = 0; i < len; i++)
{
enQueue(Q, shuju[i]);
sleep(1);
printf("%s \n", Q->data[i]);
}
}
}
void* thread_pop(void* arg)
{
int i = 0;
while (1)
{
if (isEmpty(Q))
{
printf("队列为空\n");
break;
}
else if (i < 10)
{
printf("%s\n", Q->data[i]);
i++;
}
}
}
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
显示这个警告!!!!!