首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >测量互斥锁和忙等待的效率

测量互斥锁和忙等待的效率
EN

Stack Overflow用户
提问于 2012-02-27 03:34:12
回答 1查看 1.2K关注 0票数 1

该程序将创建多个线程,其中每个线程使用for循环将共享变量递增10000,该循环在每次迭代中将共享变量递增1。互斥锁和自旋锁(忙等待)版本都是必需的。据我所知,互斥锁的工作速度应该比自旋锁快。但是我的实现给了我一个相反的答案...

这是互斥锁版本中每个线程的实现:

代码语言:javascript
运行
复制
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);
}

这是在自旋锁版本中的实现:

代码语言:javascript
运行
复制
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的增加而增大。为什么会发生这种情况?我的代码是错的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-27 03:45:29

enter_regionleave_region之间的代码不受保护。

您可以通过使它变得更加复杂来证明这一点,以确保它会自己出错。

创建一个长度为10000的布尔(检查)数组,设置为false。在enter和leave之间设置代码:

代码语言:javascript
运行
复制
if (check[sharedVar]) cout << "ERROR" << endl;
else check[sharedVar++] = true;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9456432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档