首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

读数据的线程同步有关问题

2012-10-14 
读数据的线程同步问题现在要用多个线程来读取同一个数据,而且读完之后要删除该数据项,需要做线程同步吗?如

读数据的线程同步问题
现在要用多个线程来读取同一个数据,而且读完之后要删除该数据项,需要做线程同步吗?如果不做线程同步的话可能会多个线程读取到同一个数据。如果要做线程同步应该怎么写代码?要纯C的代码,不要用到"windows.h"里面的东西或者其他的window库

[解决办法]
标准C代码不支持临界区
不过可以用volatile来代替,volatile的意思是每次都从内存中获取数据,不过这样用比较危险,建议不要用
[解决办法]
仅供参考

C/C++ code
//循环向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      2char 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;} 


[解决办法]
仅供参考

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>#ifdef WIN32    #include <windows.h>    #include <io.h>    #include <process.h>    #define  MYVOID             void#else    #include <unistd.h>    #include <sys/time.h>    #include <pthread.h>    #define  CRITICAL_SECTION   pthread_mutex_t    #define  _vsnprintf         vsnprintf    #define  MYVOID             void *#endif//Log{#define MAXLOGSIZE 20000000#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;#ifdef WIN32void Lock(CRITICAL_SECTION *l) {    EnterCriticalSection(l);}void Unlock(CRITICAL_SECTION *l) {    LeaveCriticalSection(l);}void sleep_ms(int ms) {    Sleep(ms);}#elsevoid 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);}#endifvoid 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}static int volatile No_Loop=0;static int volatile gLock = 0;static int volatile gCounter = 0;MYVOID testThread(void *pcn) {    int n,i;    n=(int)pcn;    while (1) {        if (No_Loop==2) {            for (i = 0; i < 1000000; ) {                //以下代码无效//              if ( 0 == gLock ) {//                  gLock = n;//                  if( gLock == n ) {//                      ++i;//                      ++gCounter;//                      //if (i%100000==0) Log("%d %d\n",n,gCounter);//                      gLock = 0;//                      //if (i%100000==0) sleep_ms(10*(rand()%50));//                      continue;//                  } else sleep_ms(100);//              } else sleep_ms(100);                //应改为以下代码                InterlockedCompareExchange((void **)&gLock, (void *)n, 0);                if( gLock == n ) {                    ++i;                    ++gCounter;                    if (i%100000==0) Log("%d %d\n",n,gCounter);                    InterlockedExchange((long *)&gLock, 0);                    if (i%100000==0) sleep_ms(10*(rand()%50));                    continue;                } else sleep_ms(100);            }            sleep_ms(1000);            No_Loop=1;        }    }}int main(int argc,char * argv[]) {    int i;    srand(time(NULL));#ifdef WIN32    InitializeCriticalSection(&cs_log);#else    pthread_mutex_init(&cs_log,NULL);    pthread_t threads[4];//  void *thread_result;    int threadsN;    int rc;#endif    Log("=========BEGIN==================\n");#ifdef WIN32    _beginthread((void(__cdecl *)(void *))testThread,0,(void *)1);    _beginthread((void(__cdecl *)(void *))testThread,0,(void *)2);    _beginthread((void(__cdecl *)(void *))testThread,0,(void *)3);    _beginthread((void(__cdecl *)(void *))testThread,0,(void *)4);#else    threadsN=0;    rc=pthread_create(&(threads[threadsN++]),NULL,testThread,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);    rc=pthread_create(&(threads[threadsN++]),NULL,testThread,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);    rc=pthread_create(&(threads[threadsN++]),NULL,testThread,(void *)3);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);    rc=pthread_create(&(threads[threadsN++]),NULL,testThread,(void *)4);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);#endif    sleep_ms(1000);    No_Loop=2;    i=0;    while (1) {        sleep_ms(1000);        if (No_Loop==1) break;//    }    sleep_ms(1000);    Log("Result: %d\n",gCounter);    Log("=========END====================\n");#ifdef WIN32    DeleteCriticalSection(&cs_log);#else    pthread_mutex_destroy(&cs_log);#endif    return 0;} 


[解决办法]
1. 多个线程读同一个数据不会有问题的,问题会出在一边删除数据一边正在读,可能会造成读到的数据混乱.要保证删除之前没有线程在用或是删除之后数据仍然有效(不过不推荐)就可以了.

2. 你既然能够让程序跑起多线程来,说明你已经使用到了操作系统的多线程创建函数,为什么不再用一个操作系统提供的多线程同步操作呢.
[解决办法]
貌似CRT库对这个没有支持,可以在C里插些汇编搞定

热点排行
Bad Request.