学习分享
1、线程的概念
在一个程序里的多个执行路线就叫做线程(thread)。更准确的定义是:线程是“一个进程内部的控制序列”
一切进程至少都有一个执行线程
进程是资源分配的基本单位,线程是cpu调度的基本单位
2、CPU性能和效能
- 性能核心(P-CORE) 大核心/超大核心
- 效能核心 (E-CORE)小核心
- 大核心:随机轮片,执行的时间和顺序的随机
- 小核心:顺序执行,消耗的资源更少
在还没有超线程技术之前,单核心单位时间只允许一个线程。随机轮片(时间片轮片)技术,它保证了每个进程都能获得一定的CPU执行时间,并且能够及时响应用户的操作。当一个进程的时间片用完后,它会被放到队列的末尾,等待下一次调度,这样可以确保每个进程都有机会执行。
1秒 =1000毫秒
超线程技术:单核心多线程运行
3、并发和并行
- 并发:用户级进程(同时发生不同时进行)
- 并行:内核级进程(同时发生同时进行)
4、线程的优缺点
4.1、线程的优点
- 创建一个新线程的代价要比创建一个新进程小得多
- 与进程之间的切换相比,线程之间的切换需要操作系统做的工作至少在理论上要少很多
- 线程占用的资源要比进程少很多
4.2、线程的缺点
- 编写多线程需要更全面更深入的考虑,在一个多线程程序里,因时间分配上的细微偏差或者因共享了不该共享的变量而造成不良影响的可能性是很大的
- 调试一个多线程程序也比调试一个单线程程序困难得多
5、fork和创建新线程的区别
当一个进程执行一个fork调用的时候,会创建出进程的一个新拷贝,新进程将拥有它自己的变量和它自己的PID。这个新进程的运行时间是独立的,它在执行时几乎完全独立于创建它的进程
在进程里面创建一个新线程的时候,新的执行线程会拥有自己的堆栈(因此也就有自己的局部变量),但要与它的创建者共享全局变量、文件描述符、信号处理器和当前的子目录状态
6、线程函数库
- 与线程有关的函数构成了一个完整的系列,绝大多数函数的名字都是以“pthread_”打头的
- 要使用这些函数库,要通过引入头文件<pthread.h>
- 链接这些线程函数库时要使用编译器命令的“-pthread”选项
跨平台开发,使用线程时需要在工程(例如VS工程名右键)属性页的链接器的命令行添加-pthread
7、线程标识符
- 像每个进程有一个进程ID一样,每个线程也有一个线程ID
- 进程ID在整个系统中是唯一的,但线程不同,线程ID只在它所属的进程环境中有效
- 线程ID用pthread_t数据类型来表示,实现的时候可以用一个结构来代表pthread_t数据类型,所以可以移植的操作系统不能把它作为整数处理
8、pthread_create函数
8.1、创建线程示例
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void* thread_function(void* arg)
{
while (1)
{
cout << "child thread run" << endl;
sleep(1);
}
}
int main()
{
pthread_t threadid;
if (pthread_create(&threadid, NULL, thread_function, NULL) != 0)
{
perror("pthread_create error");
}
while (1)
{
cout << "main thread run" << endl;
sleep(1);
}
return 0;
}
8.2、创建线程示例(传参)
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void* thread_function1(void* arg)
{
int x=*(int *)arg;
while (1)
{
x++;
cout << "child1 thread run x = " <<x<<endl;
sleep(1);
}
}
void* thread_function2(void* arg)
{
int y=*(int *)arg;
while (1)
{
cout << "child2 thread run y= "<<y << endl;
sleep(1);
}
}
int main()
{
int number=0;
pthread_t threadid;
if (pthread_create(&threadid, NULL, thread_function1, &number) != 0)
{
perror("pthread_create error");
}
if (pthread_create(&threadid, NULL, thread_function2, &number) != 0)
{
perror("pthread_create error");
}
while (1)
{
cout << "main thread run number = " <<number<< endl;
sleep(1);
}
return 0;
}