两个线程之间需要数据共享,由于两个线程处理速度不一,为了防止数据丢失设置一个缓冲buffer:
#define MAX_LINE 1024 //数据buffer最大长度
#define COUNT_MAX 128 //最大数据buffer数
typedef struct
{
unsigned int buffersize; //buffer长度
char buf[MAX_LINE]; //数据数组
}BUFFER_T;
typedef struct
{
pthread_mutex_t stMutex; //线程锁
unsigned int read_point; //数据读取标记位
unsigned int write_point; //数据写标记位
unsigned int count; //缓冲区中未读取的数据数
BUFFER_T stBuffer[COUNT_MAX]; //数据数
}BUFFER_POOL;
数据定义
BUFFER_POOL gBufferPoll;
向缓冲区写入数据
void write(char *data)
{
if (gBufferPoll.count >= COUNT_MAX)
{
printf("write buffer overflow \n"); //缓冲区数据溢出
}
if (gBufferPoll.count < COUNT_MAX)
{
pthread_mutex_lock(&gBufferPoll.stMutex);
gBufferPoll.stBuffer[gBufferPoll.write_point].buffersize = strlen(data);
memcpy(gBufferPoll.stBuffer[gBufferPoll.write_point].buf, data, strlen(data));
gBufferPoll.write_point++;
gBufferPoll.count++;
pthread_mutex_unlock(&gBufferPoll.stMutex);
}
//缓冲区数据写满,从头开始覆盖
if (gBufferPoll.write_point >= COUNT_MAX)
{
pthread_mutex_lock(&gBufferPoll.stMutex);
gBufferPoll.write_point = 0;
pthread_mutex_unlock(&gBufferPoll.stMutex);
}
}
从缓冲区读取数据
void read()
{
//缓冲区有未读取的数据
if (gBufferPoll.count > 0)
{
pthread_mutex_lock(&gBufferPoll.stMutex);
gBufferPoll.read_point++;
gBufferPoll.count--;
//打印读取的数据
printf("%s",gBufferPoll.stBuffer[gBufferPoll.read_point].buf);
pthread_mutex_unlock(&gBufferPoll.stMutex);
}
//读取标记到缓冲区最后一位,从第一位开始循环
if (gBufferPoll.read_point >= COUNT_MAX)
{
pthread_mutex_lock(&gBufferPoll.stMutex);
gBufferPoll.read_point = 0;
pthread_mutex_unlock(&gBufferPoll.stMutex);
}
}