(学习笔记)gcc编译带pthread.h头文件的源码时需要的参数

今天敲了一个小程序,编译时出现错误: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


  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值