创建线程时的几个陷阱

 
前几天帮同事查一个多线程的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会阻塞直到线程退出,所以这些线程实际上是串行执行的,一个退出了,才创建下一个。当年一个同事写了一个多线程的测试程序,就是这样写的,结果没有测试出一个潜伏的问题,直到产品运行时,这个问题才暴露出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值