今天敲了一个小程序,编译时出现错误:undefined reference pthread_create
原来由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o test -lpthread test.c
再查发现编译时参数写成 -pthread 也是可以的。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#define NUMBER_OF_THREADS 10
void *print_hello_world(void *tid)
{
printf("hello world.Grettings from thread%lu\n",pthread_self());
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUMBER_OF_THREADS];
int status,i;
for(i=0;i<NUMBER_OF_THREADS;i++)
{
printf("main here.Creating thread %d\n",i);
status=pthread_create(threads+i,NULL,print_hello_world,NULL);
if(status!=0)
{
printf("Oops.pthread_create return error code%d",status);
exit(-1);
}
}
exit(0);
}
编译后输入命令:
$./test
终端输出结果如下:
swift@swift-pliot:~/Cpractice/pthread_test$ ./test
main here.Creating thread 0
main here.Creating thread 1
hello world.Grettings from thread140642204505856
main here.Creating thread 2
hello world.Grettings from thread140642196113152
main here.Creating thread 3
hello world.Grettings from thread140642187720448
main here.Creating thread 4
hello world.Grettings from thread140642059548416
main here.Creating thread 5
hello world.Grettings from thread140642177140480
main here.Creating thread 6
hello world.Grettings from thread140642168747776
main here.Creating thread 7
hello world.Grettings from thread140642160355072
main here.Creating thread 8
hello world.Grettings from thread140642151962368
main here.Creating thread 9
hello world.Grettings from thread140642143569664