Linux多线程编程初体验
直接上代码
#include "pthread.h" //线程库,线程不是通过内核实现的
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
void* thread_func(void *arg){
int *val = (int*)arg;
printf("Hi!Im a thread!
");
if(NULL != arg){
printf("argument set:%d
",*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!
");
}
sleep(1); //等待1s,否则进程先结束那么线程就无法运行了
printf("Main thread!
");
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!Im a thread! argument set:100 Main thread!
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
成为java架构师需要几年,详细说明
