Basics of C + + learning notes---Call to declare a thread function within a class

Source: Internet
Author: User

Recently, the thread pool needs to be encapsulated into a C + + class named ThreadPool. Call Pthread_create in the member function Exec_task of the class to start the thread execution routine thread_rounter. After compiling the error is as follows:

Spfs_threadpool.cpp:In member function ' int threadpool::exec_task (task*) ':

Spfs_threadpool.cpp:174:error:argument of type ' void* (threadpool::) (void*) ' does not match ' void* (*) (void*) '

There is a type mismatch problem. Because pthread_create requires a parameter type of void* (*) (void*), and Thread_rounter is a member function of a class, its type is void* (Threadpool::) (void*) member function pointer. We know that the member functions of a class will become a global function with the this pointer parameter after being processed by the compiler, so the type is doomed to be mismatched. However, if Thread_rounter is declared as a static type, the compiler converts the static form of a function into a global function without the this pointer, so its type can match the type of parameter that Pthread_create requires. However, a static member function of a class cannot access a non-static member of a class, but this can be resolved by passing the this pointer.

In conclusion, my problem can be solved in this way.

Code before the problem:

void *thread_rounter (void *)//thread execution function

{

Direct access to members of a class

}

Called in the Exec_task function:

Pthread_create (&tid,null,thread_rounter,null);//start thread execution routines

The code to fix the problem:

static void *thread_rounter (void *tmp)/thread execution function

{

Threadpool *p= (Threadpool *) tmp;

Indirect access to non-static members of a class through the P pointer

}

Called in the Exec_task function:

Pthread_create (&tid,null,thread_rounter, (void *) this);//start thread execution routines

--------------------------------------------------------------------------------------------------------------- -------

Search on the Internet there are other solutions, excerpts from the following, in order to show respect to mark the source of the article, thank the original author.

Scenario Two:

Declare the thread initiation function as a template function.

Excerpt from: HTTP://HI.BAIDU.COM/ANGELEVIL2006/ITEM/E1806EC30574FF11515058D1

[CPP]View Plaincopy
  1. Template <typename TYPE, Void (TYPE::* _runthread) () >
  2. void* _thread_t (void* param)//thread start function, declared as a template function
  3. {
  4. type* this = (type*) param;
  5. This->_runthread ();
  6. return NULL;
  7. }
  8. class MyClass
  9. {
  10. Public :
  11. MyClass ();
  12. void _runthread ();
  13. Private:
  14. pthread_t Tid;
  15. };
  16. void Myclass::_runthread ()
  17. {
  18. this->dosomething ();
  19. }
  20. Myclass::myclass ()
  21. {
  22. Pthread_create (&tid, NULL, _thread_t<myclass, &myclass::_runthread>, this );
  23. }
  24. the//function template can not only replace the type itself, but also replace the member function of the type.
  25. //Note: 1, the name can only be _runthread, can not be modified in the specified template parameters;
  26. //2, _runthread can only be public unless the _thread_t is defined inside the MyClass.

Take this scenario into my project:

Code before the problem:

void *thread_rounter (void *)//thread execution function

{

Direct access to members of a class

}

Called in the Exec_task function:

Pthread_create (&tid,null,thread_rounter,null);//start thread execution routines

The code to fix the problem:

To add a public member function:

void Run ()

{

This function replaces the execution code of the above Thread_rounter

}

Thread_rounter Modify to global template function:

Template <typename type, void (type::* Run) () >

void * Thread_rounter (void * param)

{

TYPE *p= (type*) param;

P->run ();

return NULL;

}

Called in the Exec_task function:

Pthread_create (&tid,null,thread_rounter<threadpool,&threadpool::run>, (void *) this);

Summarize:

The key to solving this problem is to find ways to make the start function pointer satisfy the void* (*) (void *) type.

Overwriting a startup function with a static member function is appropriate for situations where the source code of a class can be modified.

And the start function as a template function can also be applied to the absence of the source code of the case, write a class, the public inherit from the original class, add the Startup function as a template function.

Took three working days to write the original piece of communication daemon code from the process method to the template class, the use of the template and the derivation of the class understand a lot of truth. Another very enlightening point is how the member functions of a class are used in C + + as the starting function for creating threads.
Pthread_create is a function that creates threads under the POSIX standard, and the function prototypes are:
int Pthread_create (pthread_t *thread, pthread_attr_t *attr, void* (*start_routine) (void *), void *arg);

In C, this function is simple to use, as long as you define a function with a parameter and a return value of type void *, use the function name as an argument. If not fully compliant, you can use (void * (*) (void *)) to cast it to a function pointer that conforms to the type-checking specification. However, a non-static member function of a class implies the this pointer as the first argument, so the parameter is completely impossible to convert to void * Type, while C + + type checking is much stricter than c. Since my original code is C-style, naturally there is no type mismatch problem, now the thread start function encapsulated in a template class, and then create the thread can not meet the need.

After trying several invalid conversions, search the Web for a method: Define the thread start function as a static member function of the class (static member functions), so that the this pointer is not suppressed, and then the this pointer from the Pthread_create The last argument is passed to the start function, which casts the this pointer of the void * Type to the class pointer in the function. It seems that static member functions are somewhat magical.

=================== My name is split line ===================

With my mother and my sister in Beijing around the city for a few days, tired not. The main reason in me, did not take into account the physical factors, attached to play consumption is too big, plus oneself also no car no room, inverted bus and live hotel also want to go very far, cost time and laborious. I can't stand it any more, don't say my mother. Then go out to travel, resolutely will not be connected to more than three days, or tightly Zhang Zhang to play two days, or take a long time, take a rest. Alas, who makes us poor, but also has the money and the leisure time has not been over!

Today saw a long backlog of blog subscriptions, students began to write and continue to write more and more people. I think some articles are gloomy and depressed, because they are always ups and downs from the beginning of junior, but in the face of this many times the separate gathering calm some. I would not have cried so badly if I had not been specially recruited by Zhou Yi in disband rice. Scattered the scattered, no parting, how can there be reunion?

Or in Yourui's blog to see the small dedication to Xinjiang news, if you see him in person, will be joking that the 3,000 Yili captivity to go. After two years in the border, and then come back to learn the points topology and other mathematics can still see it? All said is the fate of impermanence, travel bumpy but can see more beautiful scenery, just don't know that the customs or is not the desert lonely smoke river Sunset Northwest?

Just went to eat, walk in the evening warm lazy air, suddenly a little autumn feeling. Think of 7 years ago my father sent me to Shangqiu a high school scene, the days are really fast ah! Old, old!

http://bbs.chinaunix.net/thread-724023-1-1.htmlhttp://blog.solrex.org/articles/ Class-member-function-as-pthread_create-argument.html

http://blog.csdn.net/luo6620378xu/article/details/8521940

Basics of C + + learning notes---Call to declare a thread function within a class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.