线程创建
创建线程需要用到pthread_create这个函数,需要注意的是这个函数不是系统提供的,而是一个库函数,所以用这个函数的时候要引入头文件<pthread.h>
函数原型
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
- thread:返回线程ID
- attr:设置线程属性,通常设置成NULL
- start_routine:线程入口函数地址,这个函数的功能主要是线程用来处理任务的
- arg:线程入口函数的参数
- Compile and link with -pthread.
链接这些函数库时,需要使用编译命令的“-lpthread”选项
代码演示:
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<unistd.h>
4 #include<stdlib.h>
5 void* thr(void* arg){
6 while(1){
7 printf("i am common thread:%p\n",pthread_self());
8 sleep(1);
9 }
10 return NULL;
11 }
12 int main(){
13 pthread_t tid;
14 void* arg;
15 int ret = pthread_create(&tid,NULL,thr,arg);
16 if(ret!=0){
17 printf("pthread_create error\n");
18 return -1;
19 }
20 while(1){
21 printf("i am main thread\n");
22 sleep(1);
23 }
24 return 0;
25 }