thread-security

First Post:

Last Update:

Word Count:
407

Read Time:
1 min

Thread Security验证

在我写lgx 服务器的时候,发现日志功能在多线程同时写入日志的时候就会发生崩溃,后面采用自己实现的线程信号量来避免该问题,但是后面在我修改http缓冲区从std::string修改为lgx::util::vessel时,我就在考虑std::string是否会存在多线程安全问题,由于涉及到内存开辟与释放,那么接下来我将会证明一下是否会存在该问题,现在我先证明一下现在的malloc, free, realloc是否会存在多线程安全问题,因为在c++中new与delete关键字只是对malloc与free函数进行了一个改编而已。

测试环境:

archlinux

glibc 2.32

gcc: 10.2.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<pthread.h>
#include<stdlib.h>
#include<stdio.h>


void *func(void *args) {
printf("start thread.%lx\n", pthread_self());
for (int i = 0; i < 0x1000; ++i) {
char *bp = malloc(i * 0x10 + 0x100);
bp = realloc(bp, i * 0x10 + 0x200);
free(bp);
}
return (void*)0;
}
int main() {
pthread_t ta[100];

for(int i = 0; i < 20; ++i) {
pthread_create(&ta[i], NULL, func, NULL);
}

for(int i = 0; i < 20; ++i) {
pthread_join(ta[i], NULL);
}
return 0;
}

开启20个线程同时堆内存进行开辟与释放,看是否发现多线程安全问题。

运行如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
┌[logan☮arch]-(~)
└> ./a.out
start thread.7f5d34cc0640
start thread.7f5d344bf640
start thread.7f5d33cbe640
start thread.7f5d2bfff640
start thread.7f5d334bd640
start thread.7f5d32cbc640
start thread.7f5d324bb640
start thread.7f5d31cba640
start thread.7f5d314b9640
start thread.7f5d30cb8640
start thread.7f5d2b7fe640
start thread.7f5d2affd640
start thread.7f5d29ffb640
start thread.7f5d2a7fc640
start thread.7f5d297fa640
start thread.7f5d28ff9640
start thread.7f5d137fe640
start thread.7f5d127fc640
start thread.7f5d12ffd640
start thread.7f5d13fff640
┌[logan☮arch]-(~)
└> echo $?
0

程序安全退出。要想证明是安全的,只能看glibc源代码。

https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#283bytes

打赏点小钱
支付宝 | Alipay
微信 | WeChat