Link to home
Start Free TrialLog in
Avatar of havman56
havman56

asked on

multithreaded mutex

hai experts,
bud in c in trouble here

i put down my question in following steps

1.i am having a class A which has vector of objects B.
2.i am having a global function i am accessing those vector objects b through objcet of A.
3.this global function is acced by some function through function pointer.
the accessing of global function is multithreaded.

then do i need to use any mutex inorder to protect my vector?

eg:
class B   class A
{         {
           m_vecorobj// vector for b objects
};        };

int foo()// global function
{
A a;
a.vectorobj.pushback();

};

int(*fptr)();
fptr=foo;

thread()
{
*fptr();
}

this thread function is called in a multithreaded way.

then do i need a mutex  before pushing or poping it!


how realy such situation works in Os level and memory managemnt.


i am very much thankful who give me answer with good explantion.

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kejin
kejin

No, absolutely not. You do *not* need a mutex (or critical section) in your example's foo() to protect the 'a'. The automatic object 'a' is defined on the stack of function foo(). Each thread has its own stack and therefore access its own instance
of 'a'. Therefore, 'a' is not a critical section you need to protect. If you put 'a' in global memory area other than stack, for instance, you defined it as

foo()
{
   static A a;
   ....
}

Then, you do need a mutex (or critical section, or other similar) to protect because could be accessed by multiple threads concurrently.
After posting the answer, I saw jkr already made the same comment
at the end of his followup. So, you should give your point to him, not me.
Avatar of havman56

ASKER

thanks for your response JKR and kejin i feel my question is ambiqous sorry i would have posted it clearer ...

class B
{
};
class A
{
public:
B m_vectorobj;
};

A a;    //object of A is global

int foo()// global function
{
// do i need to create mutex and lock the vector
a.m_vectorobj.pushback();

};

this function gets called multi threaded fashion.

so do i need create a mutex..?

explain in detail how the memory managemnt done in this program

i am again repeating sorry for my mistake and also not accepting the answer since no memory managemnt explanation is given your answer..








Please check my comment - I used a critical section instead of a mutex. It works mainly the same way, but uses less resources.
jkr

i realy understood the clear explantion provided by u but i need clear explnation of how memory mangaement takes place in threading so i awarded B grade.