Thread: Whats the proper way of creating an async method ?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    بابلی ریکا Masterx's Avatar
    Join Date
    Nov 2007
    Location
    Somewhere nearby,Who Cares?
    Posts
    497

    Whats the proper way of creating an async method ?

    Hello everyone, hope you are having a great day.
    I want to make one of my blocking methods into a non-blocking one. i.e making it asynchronous if you will.
    If I simply do something like
    Code:
    std::thread t(&MyClass::MyMethod, myobj);
    t.detach();
    will I be able to interact with this now detached thread? I mean suppose in my method (that I'm running as a second thread) I have a while loop like this :
    Code:
    while (this->IsRunning())
    {
       //lots of stuff 
    }
    Will I still be able to do
    Code:
    this->SetRunning(false)
    from my main thread and thus end the while loop (therefore ending the child thread execution and thus freeing the memory allocated in that child thread) ?

    If detaching the child thread ends all ties with the parent, how should I be doing this then?

    To give you a better idea what I'm after, here how it goes:

    Basically what I'm trying to do is that I want to create a class that runs a child thread which sits and listens/does something until something of intreset happens/is found, then it fires a callback.
    the client would simply create an instance of my class, add some callback handlers and then calls
    Code:
    myobj.start()
    and goes to do whatever else he/she wants to do.
    the thread will fire whenever something comes up and clients code gets run. user can also shutdown the processing by doing forexample
    Code:
    myobj.stop()
    which essentially sets that while loop to end.

    How should I go about this?
    Thank you all in advance
    Last edited by Masterx; 12-01-2020 at 06:13 AM.
    Highlight Your Codes
    The Boost C++ Libraries (online Reference)

    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.."
    Bill Bryson


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Async timer in C
    By 007fred50 in forum C Programming
    Replies: 3
    Last Post: 08-18-2019, 10:26 AM
  2. Creating a function in a proper way
    By actuz in forum C Programming
    Replies: 1
    Last Post: 11-11-2014, 07:04 AM
  3. Proper method of clearing buffer
    By Oldman47 in forum C++ Programming
    Replies: 14
    Last Post: 04-23-2007, 07:14 PM
  4. Recommended Method of Creating Games
    By tetsuo13 in forum Game Programming
    Replies: 17
    Last Post: 06-26-2005, 01:39 PM
  5. Replies: 3
    Last Post: 12-03-2001, 01:45 PM

Tags for this Thread