当前位置首页 > Linux知识

(二)linux线程编程学习笔记——创建线程

阅读次数:901 次  来源:admin  发布时间:

程序启动后,进程会创建主线程,此时进程就退化为主线程了,主线程退出后,地址空间就不存在了,所有的线程就会被销毁,当然也可以进行特殊的处理,确保主线程退出后,子线程依然可以运行,通过pthread_create创建子线程

一、线程ID

每一个线程都有一个唯一的编号,类型为pthread_t,也就是一个无符号长整形。

二、获取当前线程id

1 pthread_t pthread_self(void)

三、头文件及编译

在linux下进行多线程编程时,需要包含pthread.h头文件,编译时需要带-l参数,例如:

gcc test.c -lpthread -o test

三、创建线程

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

第一个参数:pthread_t是一个传出参数,就是创建线程后生成的线程id

第二个参数:pthread_attr_t是线程属性,如果没有特殊要求,一般赋值NULL

第三个参数:void *(*start_routine) 自定义个线程执行函数,是函数地址

第四个参数:void *arg 给线程执行函数传递的参数,如果多个参数可以传递一个结构体

四、练习

创建文件thread_create.c,内容如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<pthread.h>
 4 void* callback(void* arg){
 5    printf("子线程id:%ld\n",pthread_self());
 6    for(int i=0;i<5;i++){
 7      printf("子线程:%d\n",i);
 8    }
 9    return NULL;
10 };
11 int main(){
12         pthread_t tid;
13         pthread_create(&tid,NULL,callback,NULL);
14         printf("主线程id:%ld\n ",pthread_self());
15         for(int i=0;i<5;i++){
16           printf("主线程:%d\n",i);
17         }
18   return 0;
19 }

编译命令如下:

gcc thread_create.c -lpthread -o thread_create

执行thread_create

./thread_create

输出如下:

发现只有主线程在执行,子线程没执行,原因是因为主线程在创建完子线程后继续往下执行,还不等子线程执行,程序就已经结束了,主线程就会释放空间,所以看不见子线程的输出,解决方法如下:

在主线程执行期间将自己休眠几秒钟,让子线程有机会获得cpu时间片执行,即可看见子线程执行结果

如在代码中增加sleep(3),编译期间会出现如下警告:

thread_create.c:18:2: warning: implicit declaration of function ‘sleep’ [-Wimplicit-function-declaration]

原因是缺少头文件unistd.h,完整的代码如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<pthread.h>
 4 #include<unistd.h>
 5 void* callback(void* arg){
 6    printf("子线程id:%ld\n",pthread_self());
 7    for(int i=0;i<5;i++){
 8      printf("子线程:%d\n",i);
 9    }
10    return NULL;
11 };
12 int main(){
13         pthread_t tid;
14         pthread_create(&tid,NULL,callback,NULL);
15         printf("主线程id:%ld\n ",pthread_self());
16         for(int i=0;i<5;i++){
17           printf("主线程:%d\n",i);
18         }
19         sleep(3);
20   return 0;
21 }
                    
上一篇:Linux下python安装pip-愤怒的苹果ext
下一篇:linux性能监控-CPU、Memory、IO、Network等指标的讲解