linux 下 c 语言多线程:
/* 06.3.6
Mhello1.c
Hello,world -- Multile Thread
*/
#include<stdio.h>
#include<pthread.h>
#define NUM 6 void print_msg(void* m)
{
char *cp=(char*)m;
int i;
for(i=;i<NUM;i++)
{
printf("%s",m);
fflush(stdout);
sleep();
}
} int main()
{
void print_msg(void*);
pthread_t t1,t2;
pthread_create(&t1,NULL,(void *) print_msg,(void *)"hello,");
pthread_create(&t2,NULL,(void *)print_msg,(void *)"world!\n");
pthread_join(t1,NULL);
pthread_join(t2,NULL);
}
编译时出错:以下为详细内容:
undefined reference to ‘pthread_create’ undefined reference to ‘pthread_join’
1) 在编译多线程程序时,于线程的函数都会有此错误,导致无法编译通过;(undefind reference to ‘pthread_join’)
问题的原因:pthread不是Linux下的默认的库,也就是在链接的时候,无法找到phread库中哥函数的入口地址,于是链接会失败。
解决:在gcc编译的时候,附加要加 -lpthread参数即可解决。
gcc -lpthread mhello.c -o mhello.exe
2) collect2: ld 返回 1
原因:在函数中,花括号不匹配。
解决:匹配花括号。
3)警告:传递 pthread_create 的第三个参数时不兼容的指针类型间转换,/usr/include/pthread.h:225:附注:需要类型 void * (*)(void *),但实参 类型为 void (*)(void *).
原因:pthread_create 语法错误,
根据提示查看相关文档,在第227行是第3个参数,
.