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!

猜你喜欢

转载自www.cnblogs.com/veaxen/p/9185345.html