Linux多线程编程初体验

直接上代码

#include "pthread.h"    //线程库,线程不是通过内核实现的
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"

void* thread_func(void *arg){
        int *val = (int*)arg;
        printf("Hi!I'm a thread!\n");
        if(NULL != arg){
                printf("argument set:%d\n",*val);
        }
}

int main(){
        pthread_t tid;
        int t_arg = 100;

        if(pthread_create(&tid,NULL,thread_func,&t_arg)){       //创建线程,如果成功返回0
                printf("Fail to create thread!\n");
        }

        sleep(1);       //等待1s,否则进程先结束那么线程就无法运行了
        printf("Main thread!\n");
        return 0;
}

写好代码之后使用编译命令 gcc -o pthread pthread.c会出现如下错误:

/tmp/cccBslRQ.o:在函数‘main’中:
pthread.c:(.text+0x66):对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status

这是由于pthread库不是Linux的标准库,需给编译器指定连接的库,使用gcc -o pthread pthread.c -lpthread命令,编译器会寻找libpthread.a静态库文件,并且连接到用户代码。
编译好之后运行的结果如下:

Hi!I'm a thread!
argument set:100
Main thread!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值