user-0 提问: pthread如何从子线程向主线程发消息?

回复:
user: user-1
content: 引用 8 楼 madpc 的回复:多谢楼上各位的热心回复, 受教了, 还有点问题想问一下: 1 楼上有加互斥锁和队列两种方式, 这两者的最大区别是不是前者更强调实时,后者更像是异步? 2 关于队列, 如果我用一个数组充当队列, 子线程向其追加信息, 主线程定时去取消息, 其实也可以? 1、互斥锁和队列没什么必然联系，只是如果在多线程情况下为了防止资源竞争出现问题，用互斥锁保护一下队列的元素添加删除等操作。当然， 使用队列本身就是一种异步的方式。 2、只要把队列的读写加上同步保护操作，哪个线程操作都没有问题

user: user-0
content: 多谢楼上各位的热心回复, 受教了, 还有点问题想问一下: 1 楼上有加互斥锁和队列两种方式, 这两者的最大区别是不是前者更强调实时,后者更像是异步? 2 关于队列, 如果我用一个数组充当队列, 子线程向其追加信息, 主线程定时去取消息, 其实也可以?

user: user-2
content: 引用 2 楼 madpc 的回复:[quote=引用 1 楼 mujiok2003 的回复:] 如果经常通信的话,  1.queue 2. tcp/ip 一次性通信的话: 1. future,promise, packaged_task等 2. 条件变量 + 共享变量  这方面刚接触,求详解,另外,请注意我说的是pthread[/quote] pthread 和其他thread api/library没本质区别。  http://stackoverflow.com/questions/4577961/pthread-synchronized-blocking-queue

user: user-3
content: 建一个消息队列，子线程向队列压入消息数据，主线程从队列取出消息数据

user: user-4
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; }

user: user-0
content: 引用 1 楼 mujiok2003 的回复:如果经常通信的话,  1.queue 2. tcp/ip 一次性通信的话: 1. future,promise, packaged_task等 2. 条件变量 + 共享变量  这方面刚接触,求详解,另外,请注意我说的是pthread

user: user-2
content: 如果经常通信的话,  1.queue 2. tcp/ip 一次性通信的话: 1. future,promise, packaged_task等 2. 条件变量 + 共享变量

user: user-5
content: //msg queue -lrt #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <mqueue.h>  #define MSQ_NAME "/msg_que_com"  mqd_t qid;   void* thread_entry(void* arg) {     static int i = 0;     char msg_buf[32] = {0};      while (1)     {         i++;         sleep(1);         sprintf(msg_buf, "message %d", i);         mq_send(qid, msg_buf, 32, 0);     }      mq_close(qid);     return NULL; }   int main(void) {     char* msg_ptr;     struct mq_attr attr;     pthread_t tid;      qid = mq_open(MSQ_NAME, O_CREAT | O_RDWR, 644, NULL);     if (qid < 0)     {         perror("mq_open");         exit(EXIT_FAILURE);     }      pthread_create(&tid, NULL, thread_entry, NULL);      mq_getattr(qid, &attr);     msg_ptr = calloc(1, attr.mq_msgsize);      while (1)     {         if (mq_receive(qid, msg_ptr, attr.mq_msgsize, NULL) > 0)         {             printf("msg : %s\n", msg_ptr);         }     }      pthread_join(tid, NULL);      mq_close(qid);     mq_unlink(MSQ_NAME);      return 0; }

user: user-5
content: #include <stdio.h> #include <stdlib.h> #include <pthread.h>  pthread_mutex_t mutex; pthread_cond_t cond; static char g_msg_buf[256];   void* thread_entry(void* arg) {     static int i = 0;     while (1)     {         i++;         sleep(1);         pthread_mutex_lock(&mutex);         sprintf(g_msg_buf, "message %d", i);         pthread_cond_signal(&cond);         pthread_mutex_unlock(&mutex);     }      return NULL; }   int main(void) {     pthread_t tid;      pthread_mutex_init(&mutex, NULL);     pthread_cond_init(&cond, NULL);      pthread_create(&tid, NULL, thread_entry, NULL);      while (1)     {         pthread_mutex_lock(&mutex);         pthread_cond_wait(&cond, &mutex);         printf("msg : %s\n", g_msg_buf);         pthread_mutex_unlock(&mutex);     }      pthread_join(tid, NULL);      pthread_mutex_destroy(&mutex);     pthread_cond_destroy(&cond);      return 0; }