The difference between C and C + + when using Pthread_create to create threads

Source: Internet
Author: User

The use of Pthread_create


int Pthread_create (pthread_t*, const pthread_attr_t*, void* (*) (void*), void*)


To make the g++ compile, the following methods are:

C + + prohibits assigning void pointers to other pointers at random.
So you get an error when you convert the entry of the void thread (void) function to void*, and then you call Pthread_create as a parameter, because the pthread_create argument should be a pointer like void* fun (void*) A pointer to a function.
You can modify void thread (void) to void* thread (void*), and then remove the (void*) cast at the time of the call, eliminating the error.


Cases:

void* Thread (void*) {
	int i;
	for (int i=0; i<3; i++) {
		cout << ' This is a thread ' << Endl;
	}
}

int main (int arg, char** argv) {
	pthread_t id;

	int I, ret;

	ret = pthread_create (&id, NULL, thread, NULL);

	if (ret!= 0) {
		cout << "Create thread error!" << Endl;
		Exit (1);
	}
	cout << "This is the main process" << Endl;
	Pthread_join (ID, NULL);
	return (0);
}


Change to GCC

void thread (void) {
	int i;
	for (int i=0; i<3; i++) {
		cout << ' This is a thread ' << Endl;
	}
}

int main (int arg, char** argv) {
	pthread_t id;

	int I, ret;

	ret = pthread_create (&id, NULL, (void *) thread, NULL);

	if (ret!= 0) {
		cout << "Create thread error!" << Endl;
		Exit (1);
	}
	cout << "This is the main process" << Endl;
	Pthread_join (ID, NULL);
	return (0);
}



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.