943,948 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2614
  • C++ RSS
Nov 12th, 2008
0

How can I have an object delete itself after X seconds?

Expand Post »
I'm trying to write a DNS server and I need the IP/name mappings to delete themselves after a given number of seconds. How can I accomplish that?

Thank you
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
inktri is offline Offline
1 posts
since Nov 2008
Nov 12th, 2008
0

Re: How can I have an object delete itself after X seconds?

In a timer thread do this:
C++ Syntax (Toggle Plain Text)
  1. class MyObject
  2. {
  3. public:
  4. ...
  5. void Destroy() {delete this;}
  6. ...
  7. };
  8.  
  9. MyObject* obj = new MyObject;
  10. // in a timer thread
  11.  
  12. obj.Destroy();
Last edited by Ancient Dragon; Nov 12th, 2008 at 9:14 am.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,953 posts
since Aug 2005
Nov 12th, 2008
0

Re: How can I have an object delete itself after X seconds?

Obviously the possible solution depends on the general architecture of your application (and run-time environment). In standard C++ an object life time defined with regard to the only execution thread and it's not a real time.
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Nov 14th, 2008
0

Re: How can I have an object delete itself after X seconds?

Click to Expand / Collapse  Quote originally posted by ArkM ...
Obviously the possible solution depends on the general architecture of your application (and run-time environment). In standard C++ an object life time defined with regard to the only execution thread and it's not a real time.
Hmm, i find this question very interesting, and as ArkM said, it's very run-time environment dependent...
I tried to implement a wrapper class that takes an dynamic allocated object and destroys it after X seconds. It uses the pthred library to create the timer in another thread

C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6.  
  7. using namespace std;
  8.  
  9. class Exception {};
  10.  
  11. template < class T>
  12. class ObjTimerWrapper
  13. {
  14. private:
  15. T* obj_;
  16.  
  17. int seconds_;
  18.  
  19. pthread_mutex_t mutex;
  20. pthread_t timer;
  21. void DeleteObj()
  22. {
  23. pthread_mutex_lock( &mutex );
  24. delete obj_;
  25. obj_ = 0;
  26. pthread_mutex_unlock( &mutex );
  27. }
  28.  
  29. public:
  30. ObjTimerWrapper( T* obj, unsigned int seconds):obj_(obj), seconds_(seconds)
  31. {
  32. pthread_mutex_init( &mutex, 0 );
  33. pthread_create(&timer, NULL, ObjTimerWrapper::startTimer, (void*)this );
  34. }
  35.  
  36. ~ObjTimerWrapper()
  37. {
  38. pthread_join( timer, 0 );
  39. pthread_mutex_destroy(&mutex);
  40. cout<<"destructor called"<<endl;
  41. }
  42.  
  43. void Lock() { pthread_mutex_lock( &mutex ); }
  44. void UnLock() { pthread_mutex_unlock( &mutex ); }
  45.  
  46. T* operator->()
  47. {
  48. if ( ! obj_ ) throw Exception();
  49. return obj_;
  50. }
  51. T* get()
  52. {
  53. if ( ! obj_ ) throw Exception();
  54. return obj_;
  55. }
  56.  
  57. static void* startTimer(void * arg);
  58.  
  59. };
  60.  
  61. template < class T>
  62. void *ObjTimerWrapper<T>::startTimer(void* arg)
  63. {
  64. ObjTimerWrapper* p = (ObjTimerWrapper*)arg;
  65.  
  66. sleep( p->seconds_);
  67.  
  68. p->DeleteObj();
  69.  
  70. cout<<"timer expired, object destroyed-----------"<<endl;
  71. return 0;
  72. }
  73.  
  74. class X
  75. {
  76. public:
  77. double x;
  78. void iterate();
  79. X( float xx ):x(xx){}
  80. };
  81.  
  82. void X::iterate()
  83. {
  84. for( int i = 0; i < 7; ++i )
  85. {
  86. sleep(1);
  87. }
  88. cout<<"rdy"<<endl;
  89. }
  90.  
  91.  
  92. int main ( int argc, char* argv[] )
  93. {
  94. {
  95. ObjTimerWrapper<X> myobj( new X(0), 1 );
  96. myobj.Lock();
  97. myobj->iterate();
  98. myobj.UnLock();
  99. }
  100.  
  101. cout<<"end program"<<endl;
  102. }
ObjTimerWrapper contains the dynamically alocated object ( pointer to it is stored in T* obj_)

Well, what happenes is that the timer thread that runs
void *ObjTimerWrapper<T>::startTimer(void* arg)
issues sleeps for X secs and then destroys the contained object
The destructor of ObjTimerWrapper joines with the timer thread, so the object can not be destroyed before the seconds pass ( say if ObjTimerWrapper gets out of scope it will wait in it's destructor till the timer joins )

The real problem is sycronization.
What happens if you are currently working on the contained object and the timer thread tries to destroy it? the thing is i provided a mutex locking mechanism, so that the timer thread deletes the contained object only if the mutex is unlocked. But this leaves responsablility to the client code to lock and unlock the mutex each time you call a method on the contained object ( ie , in the example,
myobj.Lock();
myobj->iterate();
myobj.UnLock(); )
kux
Reputation Points: 66
Solved Threads: 11
Junior Poster
kux is offline Offline
119 posts
since Jan 2008
Nov 14th, 2008
0

Re: How can I have an object delete itself after X seconds?

You could use the Sleep() function that will wait ex: seconds
before continue the code.

C++ Syntax (Toggle Plain Text)
  1. Sleep(5000); //Wait 5 seconds /5000 milliseconds
  2.  
  3. //Destroy/Delete object
Reputation Points: 10
Solved Threads: 1
Posting Whiz in Training
Lukezzz is offline Offline
268 posts
since Mar 2008
Nov 14th, 2008
0

Re: How can I have an object delete itself after X seconds?

That's just the point that an object per se in C++ is a passive entity. It comes into being, lives and dies with the aid of a thread (or process - an active entity) only. Of course. it's possible to set a death timer then... what? It's not an object catches a timer interrupt: it's a thread!

As soon as we understand a passive nature of an object, we can fit a key to the designated problem. Possible solutions:
1. Let the guardian thread maintains a pool of mapping objects (creates, provides access to and kills them). May be, it's the only (main) thread of the application. Remember asynchronous i/o standard logic.
2. Let every such object lives itself with its own thread (process). Remember http requests and (most of) web-server standard logics.

As kux mentioned in both (and others) cases you need (more or less) well-designed access synchronization logics. That's why I said about application architecture issues.

Apropos, Sleep function does not bear a relation to the problem: it suspends the active thread, DNS server (or what else) does nothing. As usually, classic army logics does not work in this case (if you don't know what to do now, go to bed )...
Last edited by ArkM; Nov 14th, 2008 at 10:45 am.
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Dec 8th, 2008
0

Re: How can I have an object delete itself after X seconds?

Click to Expand / Collapse  Quote originally posted by ArkM ...
That's just the point that an object per se in C++ is a passive entity. It comes into being, lives and dies with the aid of a thread (or process - an active entity) only. Of course. it's possible to set a death timer then... what? It's not an object catches a timer interrupt: it's a thread!

As soon as we understand a passive nature of an object, we can fit a key to the designated problem. Possible solutions:
1. Let the guardian thread maintains a pool of mapping objects (creates, provides access to and kills them). May be, it's the only (main) thread of the application. Remember asynchronous i/o standard logic.
2. Let every such object lives itself with its own thread (process). Remember http requests and (most of) web-server standard logics.

As kux mentioned in both (and others) cases you need (more or less) well-designed access synchronization logics. That's why I said about application architecture issues.

Apropos, Sleep function does not bear a relation to the problem: it suspends the active thread, DNS server (or what else) does nothing. As usually, classic army logics does not work in this case (if you don't know what to do now, go to bed )...
ok, i know this is an old thread and i'm not suppose to bring it up again, but I find this iteresting.
I posted before a method of providing a wrapper class that deletes an object after X seconds. It worked ok, but it forced the client to write code that explicitly locked and unlocked the mutex before and after each method call so that the object won't get destroyed while a method is called.
Now i found an article from Stroustrup that explains how to write a wraper class that wraps methos calls . This is ok, as with this you can do the lock and unlock inside the wrapper.
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6.  
  7. using namespace std;
  8.  
  9. //forward
  10. template < class T >
  11. class ObjTimerWrapper;
  12.  
  13. class Exception {};
  14.  
  15. template < class T >
  16. class Call_proxy
  17. {
  18. T* obj_;
  19. ObjTimerWrapper<T> *twrap_;
  20. public:
  21. Call_proxy( T* obj, ObjTimerWrapper<T> *twrap ): obj_(obj), twrap_(twrap) {}
  22. ~Call_proxy() { twrap_->UnLock(); }
  23. T* operator->(){ return obj_; }
  24. };
  25.  
  26. template < class T>
  27. class ObjTimerWrapper
  28. {
  29. private:
  30. T* obj_;
  31.  
  32. int seconds_;
  33.  
  34. pthread_mutex_t mutex;
  35. pthread_t timer;
  36. void DeleteObj()
  37. {
  38. pthread_mutex_lock( &mutex );
  39. delete obj_;
  40. obj_ = 0;
  41. pthread_mutex_unlock( &mutex );
  42. }
  43.  
  44. void Lock() { pthread_mutex_lock( &mutex ); }
  45. void UnLock() { pthread_mutex_unlock( &mutex ); }
  46.  
  47. friend class Call_proxy<T>;
  48.  
  49. public:
  50. ObjTimerWrapper( T* obj, unsigned int seconds):obj_(obj), seconds_(seconds)
  51. {
  52. pthread_mutex_init( &mutex, 0 );
  53. pthread_create(&timer, NULL, ObjTimerWrapper::startTimer, (void*)this );
  54. }
  55.  
  56. ~ObjTimerWrapper()
  57. {
  58. pthread_join( timer, 0 );
  59. pthread_mutex_destroy(&mutex);
  60. cout<<"destructor called"<<endl;
  61. }
  62.  
  63. Call_proxy<T> operator->()
  64. {
  65. if ( ! obj_ ) throw Exception();
  66. Lock();
  67. return Call_proxy<T>( obj_, this );
  68. }
  69. T* get()
  70. {
  71. if ( ! obj_ ) throw Exception();
  72. return obj_;
  73. }
  74.  
  75. static void* startTimer(void * arg);
  76.  
  77. };
  78.  
  79. template < class T>
  80. void *ObjTimerWrapper<T>::startTimer(void* arg)
  81. {
  82. ObjTimerWrapper* p = (ObjTimerWrapper*)arg;
  83.  
  84. sleep( p->seconds_);
  85.  
  86. p->DeleteObj();
  87.  
  88. cout<<"timer expired, object destroyed-----------"<<endl;
  89. return 0;
  90. }
  91.  
  92. class X
  93. {
  94. public:
  95. double x;
  96. void iterate();
  97. X( float xx ):x(xx){}
  98. };
  99.  
  100. void X::iterate()
  101. {
  102. for( int i = 0; i < 1; ++i )
  103. {
  104. sleep(5);
  105. }
  106. cout<<"rdy"<<endl;
  107. }
  108.  
  109.  
  110. int main ( int argc, char* argv[] )
  111. {
  112. {
  113. ObjTimerWrapper<X> myobj( new X(0), 3 );
  114. //myobj.Lock(); //this no longer required
  115. myobj->iterate();
  116. //myobj.UnLock(); //this no longer required
  117.  
  118. ObjTimerWrapper<X> mysecobj( new X(0), 9 );
  119. mysecobj->iterate();
  120.  
  121. }
  122. }
kux
Reputation Points: 66
Solved Threads: 11
Junior Poster
kux is offline Offline
119 posts
since Jan 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Card game war; completely lost
Next Thread in C++ Forum Timeline: Double Linked List I/O Undeclared???





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC