user-0 提问: 关于双线程并发的问题

回复:
user: user-1
content: 引用 楼主 u014524569 的回复:简单的程序代码（Linux下）： #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h>  #define THREAD_NUMBER 2	 int retval_hello1=2,retval_hello2=3;  void* hello1(void *arg) { 	int i,sum=0; 	char * hello_str=(char *)arg; 	//sleep(1); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	/*for(i=0;i<1000;i++){ 		sum+=i; 	} 	printf("sum1=%d\n",sum);*/ //sleep(1); printf("%s\n",hello_str); printf("%s\n",hello_str); printf("%s\n",hello_str); printf("%s\n",hello_str); 	pthread_exit(&retval_hello1); }  void* hello2(void *arg) { 	int i,j,x=0,sum=0; 	char * hello_str=(char *)arg; 	//sleep(2); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	printf("%s\n",hello_str); 	//sum+=1; 	//printf("sum2=%d\n",sum); for(i=0;i<100;i++){ 	for(j=0;j<100;j++){ 		x++; 		sum+=x; 		} 	} 	printf("sum2=%d\n",sum); printf("%s\n",hello_str); printf("%s\n",hello_str); printf("%s\n",hello_str); printf("%s\n",hello_str); 	pthread_exit(&retval_hello2); }  int main(int argc,char * argv[]) { 	int i; 	int ret_val; 	int * retval_hello[2]; 	pthread_t pt[THREAD_NUMBER]; 	const char * arg[THREAD_NUMBER]; 	arg[0]="hello world from thread1"; 	arg[1]="hello world from thread2"; 	printf("Begin to create threads..\n");  	ret_val=pthread_create(&pt[0],NULL,hello1,(void*)arg[0]); 	if(ret_val!=0) 	{ 		printf("pthread_create erro!\n"); 		exit(1); 	} 	ret_val=pthread_create(&pt[1],NULL,hello2,(void*)arg[1]); 	if(ret_val!=0) 	{ 		printf("pthread_create erro!\n"); 		exit(1); 	} 	 	printf("Now,the main thread returns.\n"); 	printf("Begin to wait for threads..\n"); 	for(i=0;i<THREAD_NUMBER;i++){ 		ret_val=pthread_join(pt[i],(void * *)&retval_hello[i]); 		if(ret_val!=0){ 			printf("pthread_join error!\n"); 			exit(1); 		} 		else{ 			printf("return vlaue is %d\n",* retval_hello[i]); 		} 	} 	 	/*ret_val=pthread_join(pt[1],(void * *)&retval_hello[1]); 	printf("return vlaue is %d\n",* retval_hello[1]);  	ret_val=pthread_join(pt[0],(void * *)&retval_hello[0]); 	printf("return vlaue is %d\n",* retval_hello[0]);*/  	printf("This is a test.\n"); 	return 0; } 	         问题1：在不同的机器中，程序的运行结果不同，有先运行完线程1再运行线程2的，有先运行线程2再运行线程1的，有互相穿插 的。这应该是时间片问题吧，但线程2的运行时间比线程1大很多，为什么会出现先运行2再运行1的？另外优先级是怎么确 定的呢？          问题2：在主线程main中，pthread_join的先后并没有决定线程的先后，甚至只用一个pthread_join都可以运行两个线程，但一个都没有却不能运行线程，为什么呢？          问题3：如果现在有两个线程，一个是读文件线程，一个是对读到的数据进行处理的线程，这两个线程是串行进行的，即先读再 处理，虽然可以不用线程编写，但用线程是不是更好一点呢？再，处理的线程的程序比较复杂，运行时间比读线程久， 那么，程序在运行时，会不会出错，比如，先运行处理，再读，或者互相穿插？那应该怎么解决呢？             望各位不吝赐教！感谢非常！   代码太长了，没有看看，简单说说  1、你的代码里面没有对线程1、2进行调度，其运行先后完全由系统调度。此外，你的线程运行时间太短了，所以偶尔出现一个完了才运行另一个的现象。至于优先级，posix有标准函数，自行百度  2、pthread_join的具体作用似乎没有弄清楚，建议百度之，简而言之就是等待某个线程。在你的程序里面，主线程处用个getchar之类的，似乎更合理  3、必须要分两个线程，因为一个是io一个是逻辑。理论上io处理速度远远低于逻辑处理速度。其实这个问题就是最简单的生产者消费者。boost有无锁解决方案

user: user-2
content: 仅供参考：//循环向a函数每次发送200个字节长度（这个是固定的）的buffer, //a函数中需要将循环传进来的buffer，组成240字节（也是固定的）的新buffer进行处理， //在处理的时候每次从新buffer中取两个字节打印 #ifdef WIN32     #pragma warning(disable:4996) #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef WIN32     #include <windows.h>     #include <process.h>     #include <io.h>     #define  MYVOID             void     #define  vsnprintf          _vsnprintf #else     #include <unistd.h>     #include <sys/time.h>     #include <pthread.h>     #define  CRITICAL_SECTION   pthread_mutex_t     #define  MYVOID             void * #endif //Log{ #define MAXLOGSIZE 20000000 #define MAXLINSIZE 16000 #include <time.h> #include <sys/timeb.h> #include <stdarg.h> char logfilename1[]="MyLog1.log"; char logfilename2[]="MyLog2.log"; static char logstr[MAXLINSIZE+1]; char datestr[16]; char timestr[16]; char mss[4]; CRITICAL_SECTION cs_log; FILE *flog; #ifdef WIN32 void Lock(CRITICAL_SECTION *l) {     EnterCriticalSection(l); } void Unlock(CRITICAL_SECTION *l) {     LeaveCriticalSection(l); } void sleep_ms(int ms) {     Sleep(ms); } #else void Lock(CRITICAL_SECTION *l) {     pthread_mutex_lock(l); } void Unlock(CRITICAL_SECTION *l) {     pthread_mutex_unlock(l); } void sleep_ms(int ms) {     usleep(ms*1000); } #endif void LogV(const char *pszFmt,va_list argp) {     struct tm *now;     struct timeb tb;      if (NULL==pszFmt||0==pszFmt[0]) return;     vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);     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);             }         } else {             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; } MYVOID 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_ms(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_ms(1);             } else {                 sleep_ms(1000);             }             if (No_Loop) break;//             wc++;             if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);         }         if (No_Loop) break;//     } #ifndef WIN32     pthread_exit(NULL); #endif } 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; } MYVOID 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_ms(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_ms(1000);             if (No_Loop) break;//             wc++;             if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);         }         if (No_Loop) break;//     } #ifndef WIN32     pthread_exit(NULL); #endif } int main() { #ifdef WIN32     InitializeCriticalSection(&cs_log);     InitializeCriticalSection(&cs_HEX );     InitializeCriticalSection(&cs_BBB ); #else     pthread_t threads[2];     int threadsN;     int rc;     pthread_mutex_init(&cs_log,NULL);     pthread_mutex_init(&cs_HEX,NULL);     pthread_mutex_init(&cs_BBB,NULL); #endif     Log("Start===========================================================\n");      BBB.head=0;     BBB.tail=0;     BBB.size=0;  #ifdef WIN32     _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);     _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2); #else     threadsN=0;     rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);     rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1); #endif      if (!access("No_Loop",0)) {         remove("No_Loop");         if (!access("No_Loop",0)) {             No_Loop=1;         }     }     while (1) {         sleep_ms(1000);         if (No_Loop) break;//         if (!access("No_Loop",0)) {             No_Loop=1;         }     }     sleep_ms(3000);     Log("End=============================================================\n"); #ifdef WIN32     DeleteCriticalSection(&cs_BBB );     DeleteCriticalSection(&cs_HEX );     DeleteCriticalSection(&cs_log); #else     pthread_mutex_destroy(&cs_BBB);     pthread_mutex_destroy(&cs_HEX);     pthread_mutex_destroy(&cs_log); #endif     return 0; }