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语言博客05--指针
    网络1911、1912 D&S第2次作业--批改总结
    JAVA课程设计——愤怒的小鸟(个人)
    JAVA课程设计——愤怒的小鸟(团队)
    网络1911、1912 C语言第1次作业批改总结
    Python--安装第三方库的方法
    Eclipse中文插件安装教程
    DS博客作业08--课程总结
    DS博客作业07--查找
    DS博客作业06--图
  • 原文地址:https://www.cnblogs.com/cindy123456/p/14028480.html
Copyright © 2011-2022 走看看