Jump to content

Threads and memory in classes


photo

Recommended Posts

Hi. I have to do a job in a class in a thread. But it seems that threads and classes do not play well. Specifically the class that carries out the action "do_blocking()" in the example below is created as uninitialised as if it is a completely new 

 

class TestClass {

  int canary;

  TestClass() {
    canary = 1;
  }

  void do_async() {
    log.message("TI: %s\n", typeinfo(this));
    log.message("Canary value = [%d]\n",canary);
    thread("do_blocking");
  }

  void do_blocking() {
    log.message("TI: %s\n", typeinfo(this));
    log.message("Canary value = [%d]\n",canary);
  }

};

The output from running "TestClass tc = new TestClass(); tc.do_async()" is

 

16:29:29 TI: TestClass 0000000007EB7150 (196608:0:0)
16:29:29 Canary value = [1]
16:29:29 TI: TestClass 0000000000000000 (196608:-1:-1)
16:29:29 Canary value = [0]

 

What I desire is that it is possible to launch a thread in a class and have that thread operate on the same object that spawned it, but it does not seem to be the case here. 

 

Am I missing something simple?

 

 

Link to comment

Hello, Angus. Long time, no see! 

 

Yup, you have to have some kind of static redirector function (it may be inside or outside class scope) to which you'll be passing your class instance. Something like this:

class TestClass {

  int canary;

  TestClass() {
    canary = 1;
  }

  void do_async() {
    log.message("TI: %s\n", typeinfo(this));
    log.message("Canary value = [%d]\n",canary);
    thread("TestClass::redirector",this);
  }

  void do_blocking() {
    log.message("TI: %s\n", typeinfo(this));
    log.message("Canary value = [%d]\n",canary);
  }

  void redirector(TestClass instance) {
    instance.do_blocking();
  }
};
Link to comment
×
×
  • Create New...