Re: how to test atomicity?
Re: how to test atomicity?
- Subject: Re: how to test atomicity?
- From: Matt Watson <email@hidden>
- Date: Sun, 19 Sep 2004 10:48:47 -0700
You're not creating 500 simultaneous threads, since pthread_join waits
for the thread to complete and the loop does create, join, create,
join...
Also, you don't need 500 threads to test atomicity. Try just creating 2
threads in main(), like:
pthread_t t1, t2;
int iX = 0;
assert(!pthread_create(&t1, NULL, test_atomic_inc, &iX));
assert(!pthread_create(&t2, NULL, test_atomic_dec, &iX));
assert(!pthread_join(t1, NULL));
assert(!pthread_join(t2, NULL));
assert(!iX);
matt.
On Sep 19, 2004, at 8:22 AM, email@hidden wrote:
#include <pthread.h>
#include <iostream>
using namespace std;
typedef int AtomicCountType;
inline static AtomicCountType AtomicIncrement( volatile
AtomicCountType *p )
{
int tmp;
// code lifted from linux
asm volatile(
"1: lwarx %0,0,%1\n"
" addic %0,%0,1\n" // addic allows r0, addi doesn't
" stwcx. %0,0,%1\n"
" bne- 1b"
: "=&r" (tmp)
: "r" ( p )
: "cc", "memory");
return( tmp );
}
inline static AtomicCountType AtomicDecrement( volatile
AtomicCountType *p )
{
int tmp;
// code lifted from linux
asm volatile(
"2: lwarx %0,0,%1\n"
" addic %0,%0,-1\n" // addic allows r0, addi doesn't
" stwcx. %0,0,%1\n"
" bne- 2b"
: "=&r" (tmp)
: "r" ( p )
: "cc", "memory");
return( tmp );
}
inline static AtomicCountType AtomicBump( volatile AtomicCountType *p,
AtomicCountType AddMe )
{
int tmp;
// code lifted from linux
asm volatile(
"3: lwarx %0,0,%1\n"
" addic %0,%0,( AddMe )\n" // addic allows r0, addi doesn't
" stwcx. %0,0,%1\n"
" bne- 3b"
: "=&r" (tmp)
: "r" ( p )
: "cc", "memory");
return( tmp );
}
void test_atomic_inc( void *pX )
{
int *piX = static_cast< int * >( pX );
for ( int iIndex = 0; iIndex < 1000000000; iIndex ++ )
{
//AtomicIncrement( piX );
( *piX ) ++;
}
pthread_exit( 0 );
}
void test_atomic_dec( void *pX )
{
int *piX = static_cast< int * >( pX );
for ( int iIndex = 0; iIndex < 1000000000; iIndex ++ )
{
//AtomicDecrement( piX );
( *piX ) --;
}
pthread_exit( 0 );
}
int main( int iArgc, char *pcArgv[] )
{
// our one true int ...
int iX = 0;
// ... and some other stuff
int iStatus = 0;
// create 500 threads, half doing incs, half doing decs
pthread_t threads[ 500 ] = { 0 };
for ( int iIndex = 0; iIndex < 500; iIndex ++ )
{
int iCreatedOK = pthread_create( &threads[ iIndex ],
NULL,
iIndex % 2 == 0 ? test_atomic_inc : test_atomic_dec,
&iX );
if ( iCreatedOK != 0 )
{
cout << "can't make thread " << iIndex << "\n";
break;
}
else
{
pthread_join( threads[ iIndex ], ( void ** )&iStatus );
}
}
// test to make sure iX is still 0 i.e. operations were really atomic
cout << "test " << ( iX == 0 ? "passed: " : "failed: " ) << iX << "\n";
pthread_exit( 0 );
}
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden