线程池学习记录1
进程是资源分配的最小单位,线程是操作系统调度执行的最小单位。
可以理解为,线程是轻量级进程。线程用于共享同一个地址空间和所有可用数据,然后同时调用多个线程相比同时调用多个进程是高效的,因为启动一个线程比一个进程快10~100倍。
1. 线程
- pthread_join用于等待一个线程的结束,也就是主线程中要是加了这段代码,就会在加代码的位置卡主,直到这个线程执行完毕才往下走。
- pthread_exit用于强制退出一个线程(非执行完毕退出),一般用于线程内部。
所以,要是想在主线程观察子线程运行了多久,一般都得pthread_exit和pthread_join结合着使用。
2. 对比互斥锁和读写锁
创建lock.c文件,文件内源码如下:
#include <pthread.h> // pthread_t
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
// #include <time.h>
#include <sys/time.h> // timeval
#include <sys/wait.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_rwlock_t rwlock;
int data = 123;
long COUNT = 10000;
void *mFunc(void *arg){
int read = 0;
for(long i = 0; i < COUNT; i++){
// 加锁
pthread_mutex_lock(&mutex);
read = data;
// 解锁
pthread_mutex_unlock(&mutex);
}
// 结束进程
pthread_exit(NULL);
}
void *rwFunc(void *arg){
int read = 0;
for(long i = 0; i < COUNT; i++){
pthread_rwlock_rdlock(&rwlock);
read = data;
pthread_rwlock_unlock(&rwlock);
}
// 结束进程
pthread_exit(NULL);
}
int main(){
// 创建两个进程,父进程中使用互斥锁读取,子进程使用读写锁读取
int pid = fork();
if(pid > 0){ // 父进程
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
//创建十个线程,并开始计时
pthread_t mtids[10];
struct timeval start;
gettimeofday(&start, NULL);
for(int i = 0; i < 100; i++){
pthread_create(&mtids[i], NULL, mFunc, NULL);
}
// 在主线程中,调用join函数,等待回收线程结束后结束计时
for(int i = 0; i < 100; i++){
pthread_join(mtids[i], NULL);
}
struct timeval end;
gettimeofday(&end, NULL);
long timediff = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
printf("互斥锁 读全部线程执行完毕,总耗时:%ld us\n", timediff);
// 回收子进程
wait(NULL);
}else if(pid == 0){ //子进程
pthread_rwlock_init(&rwlock, NULL);
//创建十个线程,并开始计时
pthread_t rwtids[10];
struct timeval start;
gettimeofday(&start, NULL);
for(int i = 0; i < 100; i++){
pthread_create(&rwtids[i], NULL, rwFunc, NULL);
}
// 在主线程中,调用join函数,等待回收线程结束后结束计时
for(int i = 0; i < 100; i++){
pthread_join(rwtids[i], NULL);
}
struct timeval end;
gettimeofday(&end, NULL);
long timediff = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
printf("读写锁 读全部线程执行完毕,总耗时:%ld us\n", timediff);
// 结束进程
exit(0);
}
return 0;
}
直接编译:
g++ lock.c -o lock
会报错:
/tmp/cc3oEk9j.o:在函数‘rwFunc(void*)’中:
lock.c:(.text+0x8a):对‘pthread_rwlock_rdlock’未定义的引用
lock.c:(.text+0x9f):对‘pthread_rwlock_unlock’未定义的引用
/tmp/cc3oEk9j.o:在函数‘main’中:
lock.c:(.text+0x144):对‘pthread_create’未定义的引用
lock.c:(.text+0x17a):对‘pthread_join’未定义的引用
lock.c:(.text+0x209):对‘pthread_rwlock_init’未定义的引用
lock.c:(.text+0x25a):对‘pthread_create’未定义的引用
lock.c:(.text+0x290):对‘pthread_join’未定义的引用
collect2: error: ld returned 1 exit status
原因是缺少pthread这个包的链接。
加上后,用以下语句编译:
gcc lock.c -o lock -pthread
然后执行:
./lock
提示:
读写锁 读全部线程执行完毕,总耗时:28026 us
互斥锁 读全部线程执行完毕,总耗时:33897 us
*** stack smashing detected ***: <unknown> terminated
已放弃 (核心已转储)
经查询,stack smashing detected的原因是:程序访问了非法的栈空间。
访问了非法的栈空间分为以下两种情况:
- 数组越界。
- 临时变量已经释放了,但是还在访问这块内存。
检查代码,发现原来是数组越界。
修改后,顺便增大数组容量,代码如下:
#include <pthread.h> // pthread_t
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
// #include <time.h>
#include <sys/time.h> // timeval
#include <sys/wait.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_rwlock_t rwlock;
int data = 123;
long COUNT = 10000;
void *mFunc(void *arg){
int read = 0;
for(long i = 0; i < COUNT; i++){
// 加锁
pthread_mutex_lock(&mutex);
read = data;
// 解锁
pthread_mutex_unlock(&mutex);
}
// 结束进程
pthread_exit(NULL);
}
void *rwFunc(void *arg){
int read = 0;
for(long i = 0; i < COUNT; i++){
pthread_rwlock_rdlock(&rwlock);
read = data;
pthread_rwlock_unlock(&rwlock);
}
// 结束进程
pthread_exit(NULL);
}
int main(){
// 创建两个进程,父进程中使用互斥锁读取,子进程使用读写锁读取
int pid = fork();
if(pid > 0){ // 父进程
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
//创建十个线程,并开始计时
pthread_t mtids[1000];
struct timeval start;
gettimeofday(&start, NULL);
for(int i = 0; i < 1000; i++){
pthread_create(&mtids[i], NULL, mFunc, NULL);
}
// 在主线程中,调用join函数,等待回收线程结束后结束计时
for(int i = 0; i < 1000; i++){
pthread_join(mtids[i], NULL);
}
struct timeval end;
gettimeofday(&end, NULL);
long timediff = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
printf("互斥锁 读全部线程执行完毕,总耗时:%ld us\n", timediff);
// 回收子进程
wait(NULL);
}else if(pid == 0){ //子进程
pthread_rwlock_init(&rwlock, NULL);
//创建十个线程,并开始计时
pthread_t rwtids[1000];
struct timeval start;
gettimeofday(&start, NULL);
for(int i = 0; i < 1000; i++){
pthread_create(&rwtids[i], NULL, rwFunc, NULL);
}
// 在主线程中,调用join函数,等待回收线程结束后结束计时
for(int i = 0; i < 1000; i++){
pthread_join(rwtids[i], NULL);
}
struct timeval end;
gettimeofday(&end, NULL);
long timediff = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
printf("读写锁 读全部线程执行完毕,总耗时:%ld us\n", timediff);
// 结束进程
exit(0);
}
return 0;
}
编译,执行。执行三次,显示结果分别为:
可以看出,总体上互斥锁和读写锁差别不大,但是某些情况下互斥锁效率会低很多。
3. 信号量
3.1 什么是信号量
线程的信号量与进程间通信中使用的信号量的概念是一样的,它是一种特殊的变量,可以被增加或减少,但对其的关键访问被保证是原子操作(atomic,是指不会被线程调度机制打断的操作,这种操作一旦开始,就一直运行到结束,中间不会切换到另一个线程)。
只有0和1两种取值的信号量叫做二进制信号量。信号量一般用于保护一段代码,使其每次只被一个执行线程执行。我们可以使用二进制信号量来完成这个工作。
3.2 信号量的接口和使用
信号量的函数都以sem_开头,线程中使用的基本信号量函数有4个,它们都声明在头文件 semaphore.h中。
1、sem_init函数:该函数用于创建信号量,其原型如下:
int sem_init(sem_t *sem, int pshared, unsigned int value);
该函数初始化由sem指向的信号对象,设置它的共享选项,并给它一个初始的整数值。pshared控制信号量的类型,如果其值为0,就表示这个信号量是当前进程的局部信号量,否则信号量就可以在多个进程之间共享,value为sem的初始值。调用成功时返回0,失败返回-1.
2、sem_wait函数:该函数用于以原子操作的方式将信号量的值减1。它的原型如下:
int sem_wait(sem_t *sem);
sem指向的对象是由sem_init调用初始化的信号量。调用成功时返回0,失败返回-1.
3、sem_post函数:该函数用于以原子操作的方式将信号量的值加1。它的原型如下:
int sem_post(sem_t *sem);
与sem_wait一样,sem指向的对象是由sem_init调用初始化的信号量。调用成功时返回0,失败返回-1.
4、sem_destroy函数:该函数用于对用完的信号量的清理。它的原型如下:
int sem_destroy(sem_t *sem);
成功时返回0,失败时返回-1.
线程分离的作用:一个可分离的线程是不可以被其他线程回收资源或者死的,他的存储器资源在他终止的时候可以由系统自动释放。所以线程的资源在线程执行结束后,线程的资源得以正确释放,从而避免了内存泄露的问题
简单的说就是在线程函数头加上 pthread_detach(pthread_self())的话,线程状态改变,在函数尾部直接 pthread_exit线程就会自动退出。省去了给线程擦屁股的麻烦。
使用Linux线程库的信号量函数,完成经典的生产者消费者模型,源码如下:
/*
使用Linux线程库的信号量函数,完成经典的生产者消费者模型
*/
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <semaphore.h>
int *buf;
int bufSize = 100;
sem_t full,empty, mutex;
int bufPtr;
int count;
// 信号量为0,说明这个信号量是当前进程的局部信号量,否则信号量就可以在多个进程之间共享。
void *producer(void * arg){
while(bufPtr < bufSize){
// 信号量模型
sem_wait(&full); // 减1
sem_wait(&mutex); // 减1
buf[++bufPtr] = bufPtr;
sem_post(&mutex); // 加1
sem_post(&empty); // 加1
}
}
void *consumer(void *arg){
while(1){
// 信号量模型
sem_wait(&empty); // 减1
sem_wait(&mutex); // 减1
count = (count + 1) % __INT32_MAX__;
printf("pid[%ld], count[%d], data[%d]\n", pthread_self(), count, buf[bufPtr--]);
sem_post(&mutex); // 加1
sem_post(&full); // 加1
}
}
int main(){
// 初始化三个信号量
sem_init(&full, 0, bufSize);
sem_init(&empty, 0, 0);
sem_init(&mutex, 0, 1);
bufPtr = -1;
count = 0;
buf = (int *) malloc(sizeof(int) * bufSize);
pthread_t ppid, cpids[5];
pthread_create(&ppid, NULL, producer, NULL);
for(int i = 0; i < 5; i++){
pthread_create(&cpids[i], NULL, consumer, NULL);
}
// 线程分离
/*线程分离的作用:一个可分离的线程是不可以被其他线程回收资源或者杀死的,他的存储器资源在他终止的时候可以由系统自动释放。
*/
pthread_detach(ppid);
for(int i = 0; i < 5; i++){
pthread_detach(cpids[i]);
}
// 主线程结束
pthread_exit(NULL);
return 0;
}
里面的线程分离写错了,pthread_detach要在线程函数里面调用,但是无伤大雅。
建议参考linux中pthread_join()与pthread_detach()详解。
上面的源码执行完显示结果:
参考:
1、linux中pthread_join()与pthread_detach()详解
2、【牛客网C++服务器项目学习】Day8-线程相关、线程锁、条件变量、信号量
3、stack smashing detected 已放弃 (核心已转储)问题原因
4、linux库函数pthread.h------pthread_rwlock_t读写锁说明