互斥锁和线程独立 [英] mutex and threads independence

查看:89
本文介绍了互斥锁和线程独立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在32核计算机上运行以下程序:

I run the following program on a 32 cores computer:

#include<iostream>
#include<algorithm>
#include<boost/thread.hpp>
using namespace std;

boost::thread_group g;
boost::mutex _mtx;

class A{
public:
    void foo()
    {   
        for(int ix = 0; ix < 10000000; ++ix)
                vec.push_back(ix);
        sort(vec.rbegin(), vec.rend());    
    }   
private:
        vector<int> vec;
};

void thread_fun()
{
    A a;
    _mtx.lock();   //line 24
    a.foo();
    _mtx.unlock();  //line 26
}

int main()
{
        g.add_thread(new boost::thread(thread_fun));
        g.add_thread(new boost::thread(thread_fun)); //line 32

        g.join_all();
}

  1. 注释了第24、26和32行,需要9秒才能完成.
  2. 仅第24行,有26条评论,而32条未评论,则还需要9秒才能完成.
  3. 没有任何评论,需要18秒才能完成

我认为这两个线程是独立的,所以在行a.foo()上是否有锁并不重要.但是,为什么呢?

I thought the two threads are independent and it doesn't matter whether there is a lock on line a.foo() or not. But it does, why?

推荐答案

互斥锁意味着一次只能有一个线程可以输入一段代码.因此,这意味着第24行的第一个线程将阻塞第二个线程,直到第一个线程到达第26行.

A mutex means that only one thread at a time can enter a piece of code. So that means that the first thread to line 24 will block the second thread until the first thread reaches line 26.

换句话说,当互斥锁都试图获取互斥锁时,它们确实使一个线程依赖于另一个线程.

In other words, the mutex does make one thread dependent on the other when they both try to acquire the mutex.

这篇关于互斥锁和线程独立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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