c++ 创建线程

来源:百度知道 编辑:UC知道 时间:2024/06/03 15:16:39
#include <pthread.h>
#include <stdio.h>
#include <iostream>
using namespace std;
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!\n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.\n");
pthread_join(id,NULL);
return (0);
}
g++ test.cpp -lpthread -o example 编译时总是出错

test.cpp:15: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’

test.cpp:15: error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)&aci

这行错了:
ret=pthread_create(&id,NULL,(void *) thread,NULL);
你要使用thread函数创建线程。注意thread是你自己定义的函数,这个函数虽然没有参数,但是后面的括号是不能省略的,应该写成thread()的形式。