此程序是否线程安全 一个线程生产者 另一个线程消费者 采用一个循环队列
仅限于1个线程写操作,1个线程读操作
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define BUF_LEN (1024 * 1024 * 1024)
#define OK 0
#define ERROR -1
char data[BUF_LEN] = {0};
long int count_write = 0;
long int count_read = 0;
int in_data(char dat)
{
int tmp = 0;
tmp = count_write + 1;
if(tmp >= BUF_LEN) tmp = 0;
if(tmp == count_read)
{
return ERROR;
}
data[count_write] = dat;
count_write ++; if(count_write >= BUF_LEN) count_write = 0;
return OK;
}
int in_datas(char *buf,int len)
{
int i = 0;
for(i = 0;i < len;i++)
{
if(ERROR == in_data(buf[i]))
{
return ERROR;
}
}
return OK;
}
int out_data(char *pdat)
{
if(count_write == count_read)
{
return ERROR;
}
*pdat = data[count_read];
count_read++; if(count_read >= BUF_LEN) count_read = 0;
return OK;
}
int get_pack(char *buf,int len)
{
static int count = 0;
char dat = 0;
while(ERROR != out_data(&dat))
{
switch(dat)
{
case '@':
memset(buf,0,len);
count = 1;
break;
case '#':
buf[0] = '@';
buf[count] = '#';
return count + 1;
break;
case '\0':
puts("---->>>>>>>>>>>>>>>>>>>>>>>>>>0");
sleep(1);
break;
default:
buf[count] = dat;
count ++;
if(count >= len) count = 0;
break;
}
}
return ERROR;
}
void *thread(void *arg)
{
int count = 0;
char buf[100] = {0};
char dat = 0;
while(1)
{
if(ERROR != get_pack(buf,99))//消费者
{
/*putchar('.');*/
printf("recv--->:%s\n",buf);
}
else sleep(1);
/*sleep(1);*/
}
return NULL;
}
int main(int argc, const char *argv[])
{
char buf[100] = {0};
int ret = 0;
int i = 0;
pthread_t tid;
pthread_create(&tid,NULL,thread,NULL);
sleep(3);
while(1)
{
sprintf(buf,"%s","@dfgdgdffdtjidtiudjrthiodnjoidrjtijsirjgegj#");
ret = in_datas(buf,strlen(buf));//生产者
if(ERROR == ret)
{
fprintf(stderr,"buf is fulled!\n");
}else i++;
/*usleep(1000);*/
i++;
if(i > 1000)
{
puts("<<<<<");
getchar(); i = 0;
}
}
return 0;
}
2020年4月4日补充:
已有重大发现
其中当count_read == BUF_LEN - 1时代码:
count_read++; <停顿365天> if(count_read >= BUF_LEN) count_read = 0;
此时写操作将永远无法判定count_write+1 == count_read,写操作将无限制循环写,导致整个循环队列无法正常运行