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 */
    

      

  • 相关阅读:
    60个生僻成语汇总
    人民网 ***讲话
    组合排序
    工具
    网络之网络设备
    《TCP协议到TCP通讯各种异常现象和分析》的学习
    Console
    RTT学习之ulog
    RTT之MQTT学习笔记
    项目管理-禅道
  • 原文地址:https://www.cnblogs.com/cindy123456/p/14028480.html
Copyright © 2011-2022 走看看