473,396 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Using a private method for threading

Xx r3negade
Consider this:

I have the class foo, with the public method thread(), and the private method bar()

In the thread() method, I would like to create a new thread, using pthread_create(), that points to bar().

Could someone tell me how to do this? I have the following code:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <pthread.h>
  3.  
  4. using namespace std;
  5.  
  6. class foo
  7. {
  8.   public:
  9.     foo()
  10.     {
  11.     }
  12.  
  13.     void thread()
  14.     {
  15.         void* g;
  16.         g = this->bar;
  17.         pthread_t thread1;
  18.         char* whatever = "hello";
  19.  
  20.         pthread_create( &thread1,
  21.                         NULL,
  22.                         &g,
  23.                         static_cast<void*>(whatever)
  24.                         );
  25.     }
  26.  
  27.   private:
  28.     void* bar(void* arg)
  29.     {
  30.         cout << "Whatever" << endl;
  31.     }
  32. };
  33.  
  34. int main()
  35. {
  36.     foo New;
  37.     New.thread();
  38.     return 0;
  39. }
  40.  
I get the following error message (line 16):
argument of type ‘void* (foo::)(void*)’ does not match ‘void*’
Apr 17 '08 #1
6 3570
TamusJRoyce
110 100+
I meant to pm instead of msg here and am new to the board. It's interesting... thanks for asking about this. I'm curious too.
Apr 17 '08 #2
gpraghuram
1,275 Expert 1GB
You should pass the address of a static function for pthread_create and this->bar is invalid to access a function in a class
Like this
static void* bar(void* arg)

Raghuram
Apr 17 '08 #3
TamusJRoyce
110 100+
But making this->bar() static removes it from being part of the class, and makes it to be like a function within a namespace of that class. You need a way to pass "this" to your new static function to be used to make the thread so it may call this->bar();

Expand|Select|Wrap|Line Numbers
  1. // pthreadsclass.h  (everything in header for 
  2. //   example)
  3.  
  4. #ifndef MYPTHREADSCLASS_H
  5.   #define MYPTHREADSCLASS_H
  6.  
  7. #include <pthread.h>
  8.  
  9. /** Change code how you see fit.  Code usable by 
  10.  *    anyone.  If you try to copywrite it as your own,
  11.  *    keeping others from using it as well, code is 
  12.  *    GPL-3 to begin with.  Else it's your code to use,
  13.  *    edit, manipulate, add to, remove from, and/or change 
  14.  *    as his/hers/your own code.  */
  15. class MyPThread
  16. {
  17.   // Keeps track if thread is suppose to be running...
  18.   bool threadIsRunning;
  19.  
  20.   // Keeps track of the thread
  21.   pthread_t threadHandle;
  22.  
  23.   // This is our most important function.  It takes "this" 
  24.   //    object as input (to be set when thread made).
  25.   //    This function is the thread which loops "void update()"
  26.   static void *updateThread(void *input)
  27.   {
  28.     // May need dynamic_ or static_ cast
  29.     MyPThread *myPThread = (MyPThread *)input;
  30.  
  31.     if (myPThread) // Always check to see if pointer !NULL
  32.     { // Makes sure thread is set to run while looping
  33.       while (myPThread->isThreadRunning())
  34.       {
  35.         myPThread->update(); // Loops, running class' 
  36.                                             //   update() method
  37.       } // End while
  38.     } // End if
  39.  
  40.     pthread_exit(NULL);
  41.   } // End updatThread() Callback Function
  42.  
  43. public:
  44.   // CONSTRUCTORS //
  45.   /** Default constructor.  Thread is made by calling
  46.    *    <CODE>startThread()</CODE> */
  47.   MyPThread()
  48.   {
  49.     threadHandle = (pthread_t)0;
  50.   } // End MyPThread() Constructor
  51.  
  52.   MyPThread(const MyPThread &thread)
  53.   {
  54.     if (this != &thread)
  55.     {
  56.       // Nothing to really copy... expand if you need it to.
  57.       threadHandle = (pthread_t)0;
  58.     } // End if
  59.   } // End MyPThread() Copy Constructor
  60.  
  61.   // DESTRUCTOR //
  62.   /** Destructor.*/
  63.   ~MyPThread()
  64.   {
  65.     // Called automatically when object
  66.     //   goes out of scope.  Makes sure
  67.     //   thread gets stopped.
  68.     stopThread();
  69.   } // End ~MyPThread() Destructor   
  70.  
  71.   // INQUIRERS //
  72.   bool isThreadRunning() const
  73.   {
  74.     return(threadIsRunning);
  75.   } // End isThreadRunning() Method
  76.  
  77.   /** Makes and starts the thread.  */
  78.   int startThread()
  79.   {
  80.     if (threadIsRunning)
  81.     {
  82.       return(1); // Failure
  83.     } // End if
  84.  
  85.     /* From https://computing.llnl.gov/tutorials/pthreads/
  86.      *   tutorial.  Look at there site to see if and how you
  87.      *   may use this block of code...  */
  88.     pthread_attr_t attr;      // Holds attributes for thread
  89.     pthread_attr_init(&attr); // Initializes attr to default attrib.'s of thread
  90.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); //Adds Joinable
  91.  
  92.     threadIsRunning = true;
  93.     int iret1 = pthread_create(&threadHandle, &attr, updateThread, (void *)this);
  94.     pthread_attr_destroy(&attr);
  95.     if (iret1)
  96.     {
  97.       threadIsRunning = false;
  98.       return(iret1); // Returns pthread_create's error if one found.
  99.     } // End if
  100.  
  101.     return(0); // Return success
  102.   } // End startThread() Method
  103.  
  104.   virtual int stopThread()
  105.   {
  106.     if (!threadIsRunning) // Returns error if pthread is not running
  107.     {
  108.       return(1);
  109.     } // End if
  110.  
  111.     int iret1 = pthread_cancel(threadHandle);
  112.     if (iret1)
  113.     {
  114.       return(iret1);
  115.     } // End if
  116.  
  117.     threadHandle = (pthread_t)0;
  118.     threadIsRunning = false;
  119.     return(0);
  120.   } // End stopThread() Method
  121.  
  122. protected:
  123.   /** Loops continually within a thread. */ 
  124.   virtual void update()
  125.   {
  126.     // Do stuff you want it too here
  127.   } // End update() Method
  128.  
  129. }; // End MyPThread() class
  130.  
  131. #endif
  132.  
  133.  
Expand|Select|Wrap|Line Numbers
  1. // main.cpp
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. // Don't have to worry what's in header.
  9. //   Just that it's there (hopefully no prob.
  10. //   or else it's fun to study)
  11. #include "pthreadclass.h"
  12.  
  13. /** : public MyPThread makes this class
  14.  *    have functions: bool isThreadRunning(), 
  15.  *    void startThread(),  and void endThread().
  16.  *    You have to have a method called
  17.  *    "void update() {  // stuff  } */
  18. class FooClass : public MyPThread
  19. {
  20.   int foo;
  21.  
  22.   // update() is my "generic" updating function.
  23.   //   feel free to change the code in the header
  24.   //   to reflect the function being bob! : D
  25.   inline void bob()
  26.   {
  27.     cout << "foo # is: " << foo 
  28.             << ", and Bob is soooo cool. " << endl;
  29.   } // End bob() Method
  30.  
  31.   /** Required method.  Must be implemented.
  32.    *    but when start() is ran, code is looped
  33.    *    about 100 times a minute within a
  34.    *    thread*/
  35.   void update()
  36.   {
  37.     bob();
  38.   } // End update() Method
  39. public:
  40.   /** Normal constructor except : MyPThread()
  41.    *    added. */
  42.   FooClass() : MyPThread()
  43.   {
  44.     foo = 1;
  45.   } // End FooClass
  46.  
  47.   /** Starts the thread */
  48.   void start()
  49.   {
  50.     startThread();
  51.   } // End start() Method 
  52.  
  53.   /** Stops the thread */
  54.   void stop()
  55.   {
  56.     stopThread();
  57.   } // End stop() Method
  58. };
  59.  
  60. // Caution:  Hit Ctrl+C to exit looping.
  61. int main()
  62. {
  63.   FooClass fooClass;
  64.  
  65.   // Should make output be repeated
  66.   //   a lot of times...
  67.   fooClass.start();
  68.  
  69.   // Waits for user input
  70.   int waitForInput;
  71.   cin >> waitForInput;
  72.  
  73.   // Probably won't work because data will
  74.   //   be repeating too fast to input data.
  75.   fooClass.stop();
  76.  
  77.   return(0);
  78. } // End main() Function
  79.  
//Sorry it's so long. But linking the static function updateThread() to how you use it in the class and keeping it private can be hard unless all the code is given in a plain, viewable format. Class theads is a feature which is much easier to implement in Java, but thankfully more powerfull in c++.

//Just don't forget to expand your thread's stack size to be large enough to hold your void update() function (I believe it's needed, but not sure). I've not found out how to do this yet. Also adding low level timer (using clock.h or otherwise) so the work update() does doesn't end up being done excessively (100 times a second).

//There are also an excellent set of algorithms which can increase and decrease how fast void update() is being called by the object itself updating how many times a second it's being called. Search "Java's graphic threads and timing" on how to do this.
Apr 17 '08 #4
Okay, I have this, and it works...
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <pthread.h>
  3.  
  4. using namespace std;
  5.  
  6. class foo
  7. {
  8.     static void* staticFunc( void* obj )
  9.     {
  10.         foo* thisObj = static_cast<foo*>(obj);
  11.         thisObj->privateFunc();
  12.     }
  13.   public:
  14.     foo()
  15.     {
  16.     }
  17.  
  18.     void thread()
  19.     {
  20.         pthread_t thread1;
  21.  
  22.         pthread_create( &thread1,
  23.                         NULL,
  24.                         staticFunc,
  25.                         this
  26.                         );
  27.     }
  28.   private:
  29.     void privateFunc()
  30.     {
  31.         cout << "In private function!  Woot!" << endl;
  32.     }
  33. };
  34.  
  35. int main()
  36. {
  37.     foo New;
  38.     New.thread();
  39.     return 0;
  40. }
  41.  
Would it be possible to pass a second parameter in staticFunc() that determines which method will be accessed?
Apr 17 '08 #5
gpraghuram
1,275 Expert 1GB
Okay, I have this, and it works...
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <pthread.h>
  3.  
  4. using namespace std;
  5.  
  6. class foo
  7. {
  8.     static void* staticFunc( void* obj )
  9.     {
  10.         foo* thisObj = static_cast<foo*>(obj);
  11.         thisObj->privateFunc();
  12.     }
  13.   public:
  14.     foo()
  15.     {
  16.     }
  17.  
  18.     void thread()
  19.     {
  20.         pthread_t thread1;
  21.  
  22.         pthread_create( &thread1,
  23.                         NULL,
  24.                         staticFunc,
  25.                         this
  26.                         );
  27.     }
  28.   private:
  29.     void privateFunc()
  30.     {
  31.         cout << "In private function!  Woot!" << endl;
  32.     }
  33. };
  34.  
  35. int main()
  36. {
  37.     foo New;
  38.     New.thread();
  39.     return 0;
  40. }
  41.  
Would it be possible to pass a second parameter in staticFunc() that determines which method will be accessed?

pthread_create takesa function pointer which has this definition
void *fun(void*)
If you want to pass more than one paramter then define a structure and then add the members which you require.
After that pass the structure as a argument to the thread function

Thanks
Raghuram
Apr 18 '08 #6
TamusJRoyce
110 100+
I'm curious how the second parameter you wish to pass would determine which method you want to call... Just for the sake of learning how to do this myself : )

But gpraghuram's correct. Or you could choose to keep the data, which determines which method you want to call, as a private variable in class foo. Set it through a public function, then use it when you run thread();

Expand|Select|Wrap|Line Numbers
  1. // Could be a class instead, functioning like a class...
  2. struct threadParam { // (struct is a class defaultly public)
  3.   foo *thisToRunThreadFuncIn;
  4.  
  5.   // Other parameters to determine which method to run
  6. }; // End threadParam struct 
  7.  
Then cast the obj as threadParam.
Apr 18 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: grutta | last post by:
I am writing a windows service that will recieve notification when a USB Device is insterted into the machine. I have used the RegisterDeviceNotification and the RegisterServiceCtrlHandlerEx with...
1
by: Alasdair | last post by:
Friends, I'm an old C programmer who upgraded to C++ but was never comfortable with it. I've recently moved to C# and love it but I obviously am missing some of the subtleties. I thought the...
0
by: Simon | last post by:
I need call a LoginUser API from MC++ dll, but when I try to call the I have always the same exception: "System.NullReferenceException: Object reference not set to an instance of an object. at...
6
by: Simon Verona | last post by:
I would normally use code such as : Dim Customer as new Customer Dim t as new threading.thread(AddressOf Customer.DisplayCustomer) Customer.CustomerId=MyCustomerId t.start Which would create...
1
by: WannaBeProgrammer | last post by:
is there a simple way to code a timer to make a warning label blink on and off? Lets say I have a form with 3 textboxes and 4 labels plus one timer object(labelTimer)and 2...
1
by: colinjack | last post by:
Hi All, I've been using the original (non-event based) asynchronous design pattern using delegates. It works fine but performance wise I know using the ThreadPool is supposed to be far better,...
6
by: Gina_Marano | last post by:
Hey All, I am using multiple child threads per main thread to download files. It sometimes appears as if the same file is being downloaded twice. I am using "lock". Am I using it correctly? Any...
2
by: lewisms | last post by:
Hello all, I am quite new to c++/. Net so please don't shoot me down for being a newbie. Any way I am trying to make a simple multithreading program that is just to learn the ideas behind it...
3
by: aine_canby | last post by:
I have a class which has a member which takes a long time to populate. Some of this member is serialised with an xml file, and some is established through a set of commands issued on the system....
5
by: iLL | last post by:
So why is it that we need to use the Invoke method when updating the GUI? The following is the way we are suppose to update GUI components: delegate void textIt(object o); public partial...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.