c++ - Threading: Do different class instances provide their own copy of their member function? -


here code:

class carl{     public:     int x;      carl(int y):x(y){      }             void compute(){         x++;                         } };   int main () {      carl c(5);                  //init     carl c2(5);                 //init       std::thread t1([&](){          for(int = 0 ; <50;i++)             c.compute();         }     );        std::thread t2([&](){          for(int = 0 ; <50;i++)             c2.compute();         }     );      t1.join();              //join     t2.join();              //join       std::cout<<c.x<<std::endl;     std::cout<<c2.x<<std::endl;        return 0; } 

output

55 55 

i aware of data races , if both threads accessing same resources, should guarded. if it's this. made 2 instances of carl named c , c2 , have own resources. made 2 threads access own compute. questions are:

  1. since both threads strictly access own resources,is thread safe , locks aren't necessary?
  2. does mean compute function being accessed c , c2 have different function address?

bonus question: planning implement multiclient file transfer. tcp ip implemented using blocking i/o , 1 listener per every connection. feel using lock guards might slow down process since on queued. algorithm/approaches?

since both threads strictly access own resources,is thread safe , locks aren't necessary?

yes, correct.

does mean compute function being accessed c , c2 have different function address?

no. functions don't need copied, each function call independent. long data operate upon not shared across threads, have no problems.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -