线程代码检查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>\n", 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\n", cnt);
    else
	printf("OK cnt=%d\n", 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 */

  

 

posted @ 2020-11-24 09:04  20181217Cindy  阅读(65)  评论(0编辑  收藏  举报