赞
踩
什么是线程?
- 轻量级的进程(LWP:light weight process),在Linux环境下线程的本质仍是进程。
- 进程:拥有独立的地址空间,拥有PCB,相当于独居。
- 线程:有PCB,但没有独立的地址空间,多个线程共享进程空间,相当于合租。
线程是系统调度进程执行的最小单位。
实际上,无论是创建进程的fork,还是创建线程的pthread_create,底层实现都是调用同一个内核函数 clone。
因此Linux内核是不区分进程和线程的, 只在用户层面上进行区分。
所以,线程所有操作函数 pthread_* 是库函数,而非系统调用。
线程优、缺点
优点相对突出,缺点在接受范围之内。Linux下由于实现方法导致进程、线程差别不是很大。
——————————————————————————————————————————
对线程的创建使用 pthread_create函数
- 函数作用:创建一个新线程
- 函数原型int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
- 返回值:成功->返回0,失败返回错误号
- 函数参数:
- pthread_t *thread:传出参数,pthread_t表示数据类型,保存系统为我们分配好的线程ID
- attr:通常传NULL,表示使用线程默认属性。若想使用具体属性也可以修改该参数。
- start_routine:函数指针,指向线程主函数(线程体),该函数运行结束,则线程结束。
- arg:线程主函数执行期间所使用的参数。
以一个例子引入
编写程序创建一个线程,并给线程传递一个结构体参数
代码如下:
- //创建子线程
- #include <stdio.h>
- #include<iostream>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <pthread.h>
- using namespace std;
- struct We
- {
- int data;
- string name;
- };
- //子进程处理函数
- void *mypthread(void *val)
- {
- cout << "child thread, pid==" << getpid() << ", id==" << pthread_self() << endl;
- struct We *p=(struct We*)val;
- cout<<"w->data:"<<p->data<<endl;
- cout<<"w->name:"<<p->name<<endl;
-
- }
- int main()
- {
- struct We w;
- w.data=51816;
- w.name="ZH&DQ";
- //函数原型
- //int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
- // void *(*start_routine) (void *), void *arg);
- pthread_t thread;
- int ret=pthread_create(&thread,NULL,mypthread,&w);
-
- if(ret!=0)
- {
- cout<<"pthread_create error,"<<strerror(ret)<<endl;
- return -1;
- }
-
-
- //为了让子进程运行起来
- sleep(2);
- cout << "main thread, pid==" << getpid() << ", id==" << pthread_self() << endl;
-
- return 0;
-
- }
-

执行结果如下:成功创建了子线程,并且子线程成功接收到主线程传递的结构体内容。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。