#include <process.h>
#include <windows.h>
class foo
{
public:
foo()
{
printf( "before sleepn" );
Sleep( 1000 );
printf( "after sleepn" );
}
void test()
{
printf( "in testn" );
}
};
foo* bar()
{
static foo a;
return &a;
}
unsigned __stdcall thread( void* )
{
foo* p = bar();
p->test();
return 0;
}
int _cdecl main( int argc, char** argv )
{
for( int i = 0; i < 10; ++i )
{
uintptr_t t = _beginthreadex( NULL, 0, thread, NULL, 0, NULL );
CloseHandle( (HANDLE)t );
}
Sleep( 5000 );
return 0;
}
///
1.以上输出的结果为
before sleep
in test
in test
in test
in test
in test
in test
in test
in test
in test
after sleep
in test
这就说明名这个10个线程中至少有9个线程没 有初始化 就会有问题。所以说多线程下要慎用静态变量,下面来看看单列模式
///
#include <iostream>
using namespace std ;
static Singleton * GetInstance ( )
static Singleton m_Instance ;
return &m_Instance ;
int GetTest ( )
return m_Test ;
Singleton ( ) { m_Test = 10 ; } ;
int main ( int argc , char * argv [ ] )
Singleton * singletonObj = Singleton :: GetInstance ( ) ;
cout << singletonObj -> GetTest ( ) << endl ;
singletonObj = Singleton :: GetInstance ( ) ;
cout << singletonObj -> GetTest ( ) << endl ;
一下这个单列模式之静态对象只会初始化一次 因为他在主函数中初始化,但是需要delete删除静态对象 如果在主线程中调用 怕子线程还在用静态变量造成程序崩溃
class Singleton
{
public :
static Singleton * GetInstance ( )
{
return const_cast < Singleton * > ( m_Instance ) ;
}
static void DestoryInstance ( )
{
if ( m_Instance != NULL )
{
delete m_Instance ;
m_Instance = NULL ;
}
}
int GetTest ( )
{
printf ("yy\n");
return m_Test ;
}
private :
Singleton ( ) { m_Test = 10 ; printf( "before sleepn" ); printf( "after sleepn" ); }
static const Singleton * m_Instance ;
int m_Test ;
} ;
const Singleton * Singleton :: m_Instance = new Singleton ( ) ;
unsigned __stdcall thread( void* )
{
Singleton * singletonObj = Singleton :: GetInstance ( ) ;
//foo* p = bar();
singletonObj->GetTest ( );
return 0;
}
int _cdecl main( int argc, char** argv )
{
for( int i = 0; i < 10; ++i )
{
uintptr_t t = _beginthreadex( NULL, 0, thread, NULL, 0, NULL );
CloseHandle( (HANDLE)t );
}
//Singleton :: DestoryInstance ( ) ;
Sleep( 5000 );
return 0;
}