xiaing_log 2016-05-27 06:39 采纳率: 40%
浏览 987

求帮助啊,线程同步问题, mutex为什么没有作用?

 #include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int accnt1 = 0;
int accnt2 = 0;
double begin=0,end=0,time=0;
int i = 1;
HANDLE hMutex;

DWORD WINAPI run(LPVOID p){
    int counter = 0;
    int temp1,temp2,r;

    begin=GetTickCount();

    do{
        WaitForSingleObject(hMutex,INFINITE);
    //  printf("%d\n",GetCurrentThreadId());
        temp1 = accnt1;
        temp2 = accnt2;
        r = rand();
        accnt1 = temp1+r;
        accnt2 = temp2-r;
        ReleaseMutex(hMutex);

        counter++;
    }while(accnt1+accnt2==0&&counter<10000000);

    end =GetTickCount();
    time = end - begin;
    printf("Thread %d counter is %d \n time is %.4f \n",i,counter,time);
    i++;

    return 0;
}

int main(){
    hMutex = CreateMutex(NULL,FALSE,NULL);
    CreateThread(NULL,0,run,NULL,0,NULL);
    CreateThread(NULL,0,run,NULL,0,NULL);

    system("PAUSE");
    return 0;
}

加了锁为什么第一个线程还是无法完成啊

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-10-04 18:34
    关注

    clude
    #include
    #include

    int accnt1 = 0;
    int accnt2 = 0;
    double begin=0,end=0,time=0;
    int i = 1;
    HANDLE hMutex;

    DWORD WINAPI run(LPVOID p){
    int counter = 0;
    int temp1,temp2,r;

    begin=GetTickCount();
    
    do{
        WaitForSingleObject(hMutex,INFINITE);
    //  printf("%d\n",GetCurrentThreadId());
        temp1 = accnt1;
        temp2 = accnt2;
        r = rand();
        accnt1 = temp1+r;
        accnt2 = temp2-r;
        ReleaseMutex(hMutex);
    
        counter++;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致