前几天帮同事查一个多线程的BUG,不到十秒钟我就找到了问题的根源。N年前我曾犯过类似的错误,呵,今天仍然有人在重复。这些问题都比较典型,把它们写出来,供新手参考吧。
l
用临时变量作为线程参数的问题。
#include
<
stdio
.h>
#include
<pthread.h>
#include
<
assert
.h>
void
*
start_routine
(
void
*
param
)
{
char
*
str
= (
char
*)
param
;
printf
(
"%s:%s/n"
, __func__,
str
);
return
NULL
;
}
pthread_t
create_test_thread
()
{
pthread_t
id
= 0;
char
str
[] =
"it is ok!"
;
pthread_create(&
id
,
NULL
,
start_routine
,
str
);
return
id
;
}
int
main
(
int
argc
,
char
*
argv
[])
{
void
*
ret
=
NULL
;
pthread_t
id
=
create_test_thread
();
pthread_join(
id
, &
ret
);
return
0;
}
|
分析:由于新线程和当前线程是并发的,谁先谁后是无法预测的。可 能
create_test_thread
已经执行完成,str已经被释放了,新线程才拿到这参数,此时它的内容已经无法确定了,自然打印出的字符串是随机的。
l
线程参数共享的问题。
#include
<
stdio
.h>
#include
<pthread.h>
#include
<
assert
.h>
void
*
start_routine
(
void
*
param
)
{
int
index
= *(
int
*)
param
;
printf
(
"%s:%d/n"
, __func__,
index
);
return
NULL
;
}
#define
THREADS_NR
10
void
create_test_threads
()
{
int
i
= 0;
void
*
ret
=
NULL
;
pthread_t
ids
[
THREADS_NR
] = {0};
for
(
i
= 0;
i
<
THREADS_NR
;
i
++)
{
pthread_create(
ids
+
i
,
NULL
,
start_routine
, &
i
);
}
for
(
i
= 0;
i
<
THREADS_NR
;
i
++)
{
pthread_join(
ids
[
i
], &
ret
);
}
return
;
}
int
main
(
int
argc
,
char
*
argv
[])
{
create_test_threads
();
return
0;
}
|
分析:由于新线程和当前线程是并发的,谁先谁后是无法预测的。i在不断变化,所以新线程拿到的参数值是无法预知的,自然打印出的字符串也是随机的。
l
虚假并发。
#include
<
stdio
.h>
#include
<pthread.h>
#include
<
assert
.h>
void
*
start_routine
(
void
*
param
)
{
int
index
= *(
int
*)
param
;
printf
(
"%s:%d/n"
, __func__,
index
);
return
NULL
;
}
#define
THREADS_NR
10
void
create_test_threads
()
{
int
i
= 0;
void
*
ret
=
NULL
;
pthread_t
ids
[
THREADS_NR
] = {0};
for
(
i
= 0;
i
<
THREADS_NR
;
i
++)
{
pthread_create(
ids
+
i
,
NULL
,
start_routine
, &
i
);
pthread_join(
ids
[
i
], &
ret
);
}
return
;
}
int
main
(
int
argc
,
char
*
argv
[])
{
create_test_threads
();
return
0;
}
|
分析:因为pthread_join会阻塞直到线程退出,所以这些线程实际上是串行执行的,一个退出了,才创建下一个。当年一个同事写了一个多线程的测试程序,就是这样写的,结果没有测试出一个潜伏的问题,直到产品运行时,这个问题才暴露出来。