zoukankan      html  css  js  c++  java
  • 线程代码检查698

    1 编译运行程序,提交截图
    2 针对自己上面的截图,指出程序运行中的问题
    3 修改程序,提交运行截图
    

     

     存在的问题:

    每次得到的答案都不相同,两个线程不互斥。

    我们没有办法预测操作系统是否将为你的线程选择一个正确的顺序。

    修改代码为:

    /* 
     * badcnt.c - An improperly synchronized counter program 
     */
    /* $begin badcnt */
    #include "csapp.h"
    
    void *thread(void *vargp);  /* Thread routine prototype */
    
    /* Global shared variable */
    volatile int cnt = 0; /* Counter */
    
    pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;//临界资源
    
    int main(int argc, char **argv) 
    {
        int niters;
        pthread_t tid1, tid2;
    
        /* Check input argument */
        if (argc != 2) { 
    	printf("usage: %s <niters>
    ", argv[0]);
    	exit(0);
        }
        niters = atoi(argv[1]);
    
        /* Create threads and wait for them to finish */
        Pthread_create(&tid1, NULL, thread, &niters);
        Pthread_create(&tid2, NULL, thread, &niters);
        Pthread_join(tid1, NULL);
        Pthread_join(tid2, NULL);
    
        /* Check result */
        if (cnt != (2 * niters))
    	printf("BOOM! cnt=%d
    ", cnt);
        else
    	printf("OK cnt=%d
    ", cnt);
        exit(0);
    }
    
    /* Thread routine */
    void *thread(void *vargp) 
    {
        int i, niters = *((int *)vargp);
        pthread_mutex_lock( &counter_mutex );
        for (i = 0; i < niters; i++) //line:conc:badcnt:beginloop
    	cnt++;                   //line:conc:badcnt:endloop
        pthread_mutex_unlock( &counter_mutex );
        return NULL;
    }
    /* $end badcnt */
    

      

  • 相关阅读:
    C# WinForm多线程(一)Thread类库
    ASP.NET执行循序
    SQLSERVER2014的内存优化表
    C# 5.0 Async函数的提示和技巧
    WPF 绑定
    使用 Cordova+Visual Studio 创建跨平台移动应用(3)
    使用 Cordova+Visual Studio 创建跨平台移动应用(2)
    使用 WPF 创建预加载控件
    A WPF/MVVM Countdown Timer
    使用WPF创建无边框窗体
  • 原文地址:https://www.cnblogs.com/cindy123456/p/14028480.html
Copyright © 2011-2022 走看看