互斥和忙等待的测量效率 [英] Measuring efficiency of Mutex and Busy waiting

查看:180
本文介绍了互斥和忙等待的测量效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该计划是每个线程增加10000使用一个for循环,在每个迭代递增1成为一个共享变量创建多个线程。这两种互斥锁和自旋锁(忙等待)版本是必需的。据我所了解,互斥版本应该工作比自旋锁更快。但是,我实现了我相反的答案......

The program is to create several threads where each thread increments a shared variable by 10000 using a for loop that increments it by 1 in every iteration. Both mutex lock and spin lock (busy waiting) versions are required. According to what I've learned, mutex version should work faster than spin lock. But what I implemented gave me an opposite answer...

这是每个线程的互斥版本inplementation:

This is the inplementation of each thread in the mutex version:

void *incr(void *tid)
{
    int i;
    for(i = 0; i < 10000; i++)
    {
        pthread_mutex_lock(&the_mutex);     //Grab the lock
        sharedVar++;    //Increment the shared variable
        pthread_mutex_unlock(&the_mutex);   //Release the lock
    }
    pthread_exit(0);
}

这是自旋锁版的实现:

And this is the implementation in the spin lock version:

void *incr(void *tid)
{
    int i;
    for(i = 0; i < 10000; i++)
    {
        enter_region((int)tid);  //Grab the lock
        sharedVar++;        //Increment the shared variable
        leave_region((int)tid);  //Release the lock
    }
    pthread_exit(0);
}
void enter_region(int tid)
{
    interested[tid] = true;     //Show this thread is interested
    turn = tid;     //Set flag
    while(turn == tid && other_interested(tid));    //Busy waiting
}
bool other_interested(int tid)    //interested[] is initialized to all false
{
    int i;
    for(i = 0; i < tNumber; i++)
        if(i != tid)
            if(interested[i] == true)   //There are other threads that are interested
                return true;
    return false;
}
void leave_region(int tid)
{
    interested[tid] = false;    //Depart from critical region
}

我还迭代线程创建和运行为几百次,以确保执行时间可以区分的过程。
例如,如果tNumber是4,我迭代计划1000次,互斥会带我2.22秒,自旋锁会带我1.35秒。所不同的成长,如tNumber增加。这究竟是为什么?是我的code错了?​​

I also iterated the process of threads creating and running for hundreds of times to make sure the execution time can be distinguished. For example, if tNumber is 4, and I iterated the program for 1000 times, mutex will take me 2.22 sec, and spin lock will take me 1.35 sec. The difference grows as tNumber increases. Why is this happening? Is my code wrong?

推荐答案

之间的code enter_region leave_region 不受保护。

The code between enter_region and leave_region is not protected.

您可以通过使问题更加复杂,以确保它会让自己了证明这一点。

You can prove this by making it more complicated to ensure that it will trip itself up.

创建设下假长度10000的布尔变量(检查)阵列。使进入和离开的code:

Create an array of bools (check) of length 10000 set up false. Make the code between enter and leave:

if (check[sharedVar]) cout << "ERROR" << endl;
else check[sharedVar++] = true;

这篇关于互斥和忙等待的测量效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆