linux多线程初学讨论

fly2sky 2012-10-25 02:33:48
初学linux多线程,基本函数的意思也都理解,想做个程序实现个几个线程同时往一个缓冲区里放数据,几个线程取数据,程序放上来,希望能抛砖引玉,忘高手们给挑挑毛病,讲讲逻辑过程最好,看我理解的是否正确!谢谢!

#include<stdio.h>
#include<pthread.h>
#define SIZE 4
struct product
{
pthread_mutex_t mutex;
pthread_cond_t notfull;
pthread_cond_t notempty;
int pos;
int buf[SIZE];
};

void init(struct product *t)
{
pthread_mutex_init(&t->mutex,NULL);
pthread_cond_init(&t->notfull,NULL);
pthread_cond_init(&t->notempty,NULL);
t->pos =-1;
}

void put(struct product *t,int data)
{
pthread_mutex_lock(&t->mutex);
if((t->pos+1)>(SIZE-1))
pthread_cond_wait(&t->notfull,&t->mutex);
t->pos = t->pos +1;
t->buf[t->pos] = data;
printf("Thread %d put a data:%d to pos%d\n",pthread_self(),data,t->pos);
pthread_cond_broadcast(&t->notempty);
pthread_mutex_unlock(&t->mutex);
}

void get(struct product *t)
{
int rtntemp;
pthread_mutex_lock(&t->mutex);
if(t->pos<0)
pthread_cond_wait(&t->notempty,&t->mutex);
printf("Thread %d get a data:%d from pos%d\n",pthread_self(),t->buf[t->pos],t->pos);
rtntemp = t->buf[t->pos];
t->pos = t->pos -1;
pthread_cond_broadcast(&t->notfull);
pthread_mutex_unlock(&t->mutex);
}

struct product pdt;
void *putter()
{
int n;
for(n=0;n<8;n++)
put(&pdt,n);
}

void *getter()
{
int n;
for(n=0;n<8;n++)
get(&pdt);
}


int main(void)
{
pthread_t pt1,pt2,gt1,gt2;
void *retval;
init(&pdt);
pthread_create(&pt1,NULL,putter,0);
pthread_create(&pt2,NULL,putter,0);
pthread_create(>1,NULL,getter,0);
pthread_create(>2,NULL,getter,0);

pthread_join(pt1,&retval);
pthread_join(pt2,&retval);
pthread_join(gt1,&retval);
pthread_join(gt2,&retval);
return 0;
}

...全文
112 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2012-10-25
  • 打赏
  • 举报
回复
仅供参考
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <process.h>
#include <io.h>
//Log{
#define MAXLOGSIZE 10000000
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
char logstr[16000];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;

if (NULL==pszFmt||0==pszFmt[0]) return;
if (-1==_vsnprintf(logstr,ARRSIZE(logstr),pszFmt,argp)) logstr[ARRSIZE(logstr)-1]=0;
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
flog=fopen(logfilename1,"a");
if (NULL==flog) return;
}
fclose(flog);
}
}
void Log(const char *pszFmt,...) {
va_list argp;

Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
#define ASIZE 200
#define BSIZE 240
#define CSIZE 2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
int head;
int tail;
int size;
char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
int i,j,k;
char binstr[80];

Lock(&cs_HEX);
for (i=0;i<len;i++) {
if (0==(i%16)) {
sprintf(binstr,"%03d %04x -",cn,i);
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
} else if (15==(i%16)) {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
sprintf(binstr,"%s ",binstr);
for (j=i-15;j<=i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
} else {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
}
}
if (0!=(i%16)) {
k=16-(i%16);
for (j=0;j<k;j++) {
sprintf(binstr,"%s ",binstr);
}
sprintf(binstr,"%s ",binstr);
k=16-k;
for (j=i-k;j<i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
}
Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

lent=0;
Lock(cs);
if (fbuf->size>=len) {
lent=len;
if (fbuf->head+lent>BSIZE) {
len1=BSIZE-fbuf->head;
memcpy(buf ,fbuf->data+fbuf->head,len1);
len2=lent-len1;
memcpy(buf+len1,fbuf->data ,len2);
fbuf->head=len2;
} else {
memcpy(buf ,fbuf->data+fbuf->head,lent);
fbuf->head+=lent;
}
fbuf->size-=lent;
}
Unlock(cs);
return lent;
}
void thdB(void *pcn) {
char *recv_buf;
int recv_nbytes;
int cn;
int wc;
int pb;

cn=(int)pcn;
Log("%03d thdB thread begin...\n",cn);
while (1) {
Sleep(10);
recv_buf=(char *)Cbuf;
recv_nbytes=CSIZE;
wc=0;
while (1) {
pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
if (pb) {
Log("%03d recv %d bytes\n",cn,pb);
HexDump(cn,recv_buf,pb);
Sleep(1);
} else {
Sleep(1000);
}
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

Lock(cs);
lent=len;
if (fbuf->size+lent>BSIZE) {
lent=BSIZE-fbuf->size;
}
if (fbuf->tail+lent>BSIZE) {
len1=BSIZE-fbuf->tail;
memcpy(fbuf->data+fbuf->tail,buf ,len1);
len2=lent-len1;
memcpy(fbuf->data ,buf+len1,len2);
fbuf->tail=len2;
} else {
memcpy(fbuf->data+fbuf->tail,buf ,lent);
fbuf->tail+=lent;
}
fbuf->size+=lent;
Unlock(cs);
return lent;
}
void thdA(void *pcn) {
char *send_buf;
int send_nbytes;
int cn;
int wc;
int a;
int pa;

cn=(int)pcn;
Log("%03d thdA thread begin...\n",cn);
a=0;
while (1) {
Sleep(100);
memset(Abuf,a,ASIZE);
a=(a+1)%256;
if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
send_buf=(char *)Abuf;
send_nbytes=ASIZE;
Log("%03d sending %d bytes\n",cn,send_nbytes);
HexDump(cn,send_buf,send_nbytes);
wc=0;
while (1) {
pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
Log("%03d sent %d bytes\n",cn,pa);
HexDump(cn,send_buf,pa);
send_buf+=pa;
send_nbytes-=pa;
if (send_nbytes<=0) break;//
Sleep(1000);
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int main() {
InitializeCriticalSection(&cs_log );
Log("Start===========================================================\n");
InitializeCriticalSection(&cs_HEX );
InitializeCriticalSection(&cs_BBB );

BBB.head=0;
BBB.tail=0;
BBB.size=0;

_beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
_beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);

if (!access("No_Loop",0)) {
remove("No_Loop");
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
while (1) {
Sleep(1000);
if (No_Loop) break;//
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
Sleep(3000);
DeleteCriticalSection(&cs_BBB );
DeleteCriticalSection(&cs_HEX );
Log("End=============================================================\n");
DeleteCriticalSection(&cs_log );
return 0;
}
fly2sky 2012-10-25
  • 打赏
  • 举报
回复
想明白了,结贴,我认为是这样的,是boradcast这里出了问题,当有两个put同时等待的时候,这个时候pos为3的话,boradcast就会让两个线程都得到释放信好,这两个线程相继往下运行,就会出现pos大于SIZE的情况,同样get的时候也可能导致pos小于0的情况。
qq120848369 2012-10-25
  • 打赏
  • 举报
回复
太基础了,还是回去闷头学吧。
fly2sky 2012-10-25
  • 打赏
  • 举报
回复
Thread -1208394832 put a data:0 to pos0
Thread -1208394832 put a data:1 to pos1
Thread -1208394832 put a data:2 to pos2
Thread -1208394832 put a data:3 to pos3
Thread -1229374544 get a data:3 from pos3
Thread -1229374544 get a data:2 from pos2
Thread -1229374544 get a data:1 from pos1
Thread -1229374544 get a data:0 from pos0
Thread -1208394832 put a data:4 to pos0
Thread -1208394832 put a data:5 to pos1
Thread -1208394832 put a data:6 to pos2
Thread -1208394832 put a data:7 to pos3
Thread -1218884688 put a data:0 to pos4
Thread -1229374544 get a data:0 from pos4
Thread -1229374544 get a data:7 from pos3
Thread -1229374544 get a data:6 from pos2
Thread -1229374544 get a data:5 from pos1
Thread -1239864400 get a data:4 from pos0
Thread -1218884688 put a data:1 to pos0
Thread -1218884688 put a data:2 to pos1
Thread -1218884688 put a data:3 to pos2
Thread -1218884688 put a data:4 to pos3
Thread -1239864400 get a data:4 from pos3
Thread -1218884688 put a data:5 to pos3
Thread -1239864400 get a data:5 from pos3
Thread -1218884688 put a data:6 to pos3
Thread -1239864400 get a data:6 from pos3
Thread -1218884688 put a data:7 to pos3
Thread -1239864400 get a data:7 from pos3
Thread -1239864400 get a data:3 from pos2
Thread -1239864400 get a data:2 from pos1
Thread -1239864400 get a data:1 from pos0

现在结果是这样的~~~
fly2sky 2012-10-25
  • 打赏
  • 举报
回复
我擦 一发帖就看到一个低级错误,一个应该是 unlock写成lock了
fly2sky 2012-10-25
  • 打赏
  • 举报
回复
现在执行结果是:
Thread -1208501328 put a data:0
Thread -1208501328 put a data:1
Thread -1208501328 put a data:2
Thread -1208501328 put a data:3
Thread -1208501328 put a data:4
Thread -1208501328 put a data:5
Thread -1208501328 put a data:6
Thread -1208501328 put a data:7
Thread -1208501328 put a data:8
Thread -1208501328 put a data:9
Thread -1208501328 put a data:10
Thread -1208501328 put a data:11
Thread -1208501328 put a data:12
Thread -1208501328 put a data:13
Thread -1208501328 put a data:14


然后就没有然后了,我有点想不通,为什么就没然后了呢

64,652

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧