1. 什么是线程
线程是比进程更小的能独立运行的基本单位,线程基本上不拥有系统资源
一个进程下可以开多个线程,这些线程是并发的
查看线程命令
命令 | 含义 |
---|---|
ps -T -p | -T开启线程查看 |
top -H -p | -H开启线程查看 |
文件书写
文件 | 含义 |
---|---|
/proc/{PID}/task/ | 线程默认的名字和进程名相同 |
/proc/{PID}/task/{tid}/comm | 线程名 |
2. 操作
操作 | 函数 |
---|---|
线程标识 | pthread_t pthread_self(void) |
线程创建 | int pthread_create(pthread_t * tidp, pthread_attr_t * attr, void *(*start_rtn)(void), void * arg) |
子线程终止 | void pthread_exit(void* retval) |
线程合并 | int pthread_join(pthread_t tid, void **retval) |
线程分离 | int pthread_detach(pthread_t tid) |
发送信号 | int pthread_kill(pthread_t tid, int sig) |
线程标识 pthread_self()
线程创建 pthread_create(线程id指针 , NULL, 函数指针, 函数参数)
2.1 线程的并发
创建一个线程,让主进程和这个线程并发执行:
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;
void* handle(void*){
for(int i=0;i<10;++i){
sleep(1);
cout << pthread_self() << ":" << i << endl;
}
return NULL;
}
int main(){
cout << getpid() << endl; // pid
cout << pthread_self() << endl; // 线程标识
pthread_t tid;
pthread_create(&tid,NULL,handle,NULL); // 创建一个线程,handle传指针并返回指针,是这个线程做的事
// 主进程也做这个
for(int i=0;i<10;++i){
sleep(1);
cout