在编译Linux下多线程程序的时候出现错误信息,
写好代码,进行编译时,出现如下错误提示信息:
thread.c:(.text+0xae): undefined reference to `pthread_create'
thread.c:(.text+0xf3): undefined reference to `pthread_create'
thread.c:(.text+0x127): undefined reference to `pthread_join'
thread.c:(.text+0x13a): undefined reference to `pthread_join'
collect2: ld returned 1 exit status
|
linux下的多线程程序代码如下:
/* thread.c */
#include <stdio.h>
#include <pthread.h>
/* thread 1 */
void thread1(void)
{
int i = 0;
for (i=0; i<6; i++)
{
printf("This is a pthread1.\n");
if (i == 2)
pthread_exit(0);
sleep(1);
}
}
/* thread 2 */
void thread2(void)
{
int i;
for (i=0; i<3; i++)
printf("This is a pthread2.\n");
pthread_exit(0);
}
int main(void)
{
pthread_t id1, id2;
int i, ret;
/* Create Thread 1 */
ret = pthread_create(&id1, NULL, (void *)thread1, NULL);
if (ret != 0)
{
printf("Create pthread error!\n");
exit(1);
}
/* Create Thread 2 */
ret = pthread_create(&id2, NULL, (void *)thread2, NULL);
if (ret != 0)
{
printf("Create pthread error!\n");
exit(1);
}
/* Wait Thread Terminate */
pthread_join(id1, NULL);
pthread_join(id2, NULL);
exit(0);
}
|
错误原因: pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
解决之道:在编译中要加 -lpthread参数,类似于在使用是的参数 -lm.
gcc thread.c -lpthread
thread.c为源文件,不要忘了加上头文件#include
最后输出如下:
[root@MUPF-SST-A xudong]# ./a.out
This is a pthread1.
This is a pthread2.
This is a pthread2.
This is a pthread2.
This is a pthread1.
This is a pthread1.
|
阅读(7562) | 评论(0) | 转发(0) |