A common problem during thread creation: Invalid conversion from 'void * 'to 'void * (*) (void *)

Source: Internet
Author: User

Author: gnuhpc

Source: http://www.cnblogs.com/gnuhpc/

Void main_thread (void * PTR)
{
Char * message1 = "thread 1 ";
Char * message2 = "thread 2 ";
Pthread_t thread3, thread4;
Int iret3, iret4;
Iret3 = pthread_create (& thread3, null, (void *) & print_message_function, (void *) message1 );

Iret4 = pthread_create (& thread4, null, (void *) & print_message_function, (void *) message2 );

}
Void print_message_function (void * PTR)
{
Char * message;
Message = (char *) PTR;
Printf ("% s/n", message );
}
The above code is compiled using G ++ with the following error:
Invalid conversion from 'void * 'to 'void * (*) (void *)
Note that the prototype of the thread function is created in POSIX definition:
Extern int pthread_create (pthread_t * _ restrict _ threadp,
_ Const pthread_attr_t * _ restrict _ ATTR,
Void * (* _ start_routine) (void *),
Void * _ restrict _ Arg) _ Throw;
The third parameter in this call is to load a function. This function has a parameter that can be passed in and returns a common pointer.
Let's take a look at how the original function called this prototype, basically similar to the call method:
(Void *) & main_thread
The meaning of this expression: Take a pointer to the main_thread function and convert it into a common pointer.
This means that the above two things are obviously not the same, so the correct call method is
Iret3 = pthread_create (& thread3, null, print_message_function, (void *) message1 );

The processing function is defined as follows:
Void * print_message_function (void * PTR)

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.