如果使用mutex.lock在lock成功之前不会有两个同时lock?这个是有可能产生的好不,我以前使用sleep来防止,但是现在对时间要求高,没法那么弄所以怎么弄?

解决方案 »

  1.   


    在lock成功之前不会有两个同时lock?-----------你没看出你话的自相矛盾么?
      

  2.   

    在同一个进程的多个线程,只有一个线程会得到Mutex,直到这个线程调用ReleaseMutex后,其他线程才会得到这个Mutex,以此类推。
      

  3.   

    Handle hmtx;
    hmtx=CreateMutex(0,0,0);
    unsigned threadID;
    _beginthreadex(0,0,process,0,&threadID);
    process(void* pdevice)
    {
    waitForSingleObject(hmtx,INFINITE);
    //执行运算段落
    ReleaseMutex(hmtx);
    }
    我是这样来进行操作的,process不止一个,运行一会就停止了,我认为是等待时候两个都拿到数据使互斥量变成-1导致死锁了,不知道是不是这样
      

  4.   

    _beginthreadex(0,0,process,this,0,&threadID);这个打错了
      

  5.   

    Handle hmtx;
    hmtx=CreateMutex(0,0,0);
    unsigned threadID;
    _beginthreadex(0,0,process,0,&threadID);
    process(void* pdevice)
    {
    waitForSingleObject(hmtx,INFINITE);
    //执行运算段落
    ReleaseMutex(hmtx);
    }
    我是这样来进行操作的,process不止一个,运行一会就停止了,我认为是等待时候两个都拿到数据使互斥量变成-1导致死锁了,不知道是不是这样
    如果两个线程同时获得mutex,那么,这就是“锁不住”,连锁都锁不住,何谈死锁?而且,也不可能有两个线程同时获得mutex,windows内核很健壮,不会出这种bug
      

  6.   

    互斥量可理解为引用为1的信号量,怎么会被两个锁定呢?计算机运行的单位是机器指令,一句代码可能是多个机器指令,但是
    对引用计数操作不会被拆分了,内部肯定处理过了,用了这么久的东西 你现在产生怀疑了。
    先把 你产生这种疑问的原因写清楚吧,你的疑问有没有根据都不一定,让大家怎么讨论Handle hmtx;
    hmtx=CreateMutex(0,0,0);
    unsigned threadID;
    _beginthreadex(0,0,process,0,&threadID);
    process(void* pdevice)
    {
    waitForSingleObject(hmtx,INFINITE);
    //执行运算段落
    ReleaseMutex(hmtx);
    }
    我是这样来进行操作的,process不止一个,运行一会就停止了,我认为是等待时候两个都拿到数据使互斥量变成-1导致死锁了,不知道是不是这样
      

  7.   

    我看有些书上说是waitfor等到之后会对计数器数据减一,如果原来是1,两次减掉变成-1,然后释放掉变成0,不就永远不会再被触发了嘛
      

  8.   


    都变成0了你认为他还能再减吗?你就有一块橡皮,借给你同学了,另一个同学来借你拿什么借给他,而借的时候处理下(实现自己找)只有有资源的时候才能借,那么其他线程即便轮到了时间片因为没有资源waitforsingleobject也是一直阻塞的。
      

  9.   


    mutex 其实返回值只有两个: 成功 或者 超时。当然,貌似还有一个: 被遗弃。
    其实,被遗弃也是成功,某线程遗弃了资源,系统将其分配给了当前这个线程,这个线程的wait函数返回错误,但是,错误值如果是被遗弃,其实是遗弃给了当前线程。就像你捡了个宝贝,而不是从别人手里接过宝贝,但结果是一样的。
      

  10.   

    特供调试多线程程序的“基础设施”给楼主使用:
    //循环向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;
    }
      

  11.   

    您给的例子是有加  sleep_ms(1000);延时的,我现在就是不要延时
      

  12.   

    早晚你会用上的。我今天在这里大胆预言!我说了我以前用的是加sleep延时来保证同步的,现在因为实时性要求高了需要不能用sleep来延迟我早用上了,不用晚了。
      

  13.   

    楼主,你想多了。这是操作系统的事情。始终只会有一个线程能锁住mutex,操作系统提供给你API就已经保证了这一点。不然你用线程API干什么?还不如自己模拟呢