Linux学习-线程的创建和终止-(出现错误-undefined reference to 'pthread_create')

在下面的例程中创建了5个线程,这 5 个线程和主线程并发执行,主线程创建完线程后调用 pthread_exit()函数退出线程,其它线程分别打印当前线程的序号。当主线程先于其它进程执行 pthread_exit()时,进程不会退出,而是最后一个线程完成时才会进程退出。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid){ /* 线程函数 */
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid); /* 打印线程对应的参数 */
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){ /* 循环创建 5 个线程 */
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); /* 创建线程 */
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
printf("In main: exit!\n");
pthread_exit(NULL); /* 主线程退出 */
return 0;
}


程序中主线程调用了 pthread_exit()函数并不会将整个进程终止,而是最后一个线程调用 pthread_exit()时程序才完成运行。


    用GCC进行编译:

gcc a.c -o a

    出现错误:

undefined reference to 'pthread_create';

    解决方法:这里是没有链接到库,应该添加-lpthread参数,GCC编译的语句应该为:

gcc a.c -o a -lpthread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值