gcc testsync2.c -D_GNU_SOURCE  -march=native -lpthread -o testsync2.exe

//http://www.alexonlinux.com/

pid_t gettid( void )
{
    return syscall( __NR_gettid );
}
void *thread_routine( void *arg )
{
    int i;
    int proc_num = (int)(long)arg;
    cpu_set_t set;

    CPU_ZERO( &set );
    CPU_SET( proc_num, &set );

    if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
    //if (sched_setaffinity(0, sizeof( cpu_set_t ), &set ))
    {
        perror( "sched_setaffinity" );
        return NULL;
    }

    for (i = 0; i < INC_TO; i++)
    {
        __sync_fetch_and_add( &global_int, 1 );
    }
    return NULL;
}

 

void *test_func1(void *arg)
{
    int proc_num = (int)(long)arg;
    cpu_set_t set;

    CPU_ZERO( &set );
    CPU_SET( proc_num, &set );
    printf("proc_num=(%d)\n",proc_num) ;
    if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
    {
        perror( "sched_setaffinity" );
        return NULL;
    }

    int i=0,idy=0;
    for(i=0;i<100000000;++i){
        while (__sync_lock_test_and_set(&(ispin), 1))
            while (ispin)
                __asm volatile ("pause" ::: "memory");

        for(idy=0;idy<10;idy++)
        {
            (iGlobal[idy].idata) ++  ;
            //iGlobal[idy] ++  ;
        }

        __sync_lock_release(&(ispin));
    }
    return NULL;
} //test_func1

 

int main()
{
    int procs = 0;
    int i;
    pthread_t *thrs;

    // Getting number of CPUs
    procs = (int)sysconf( _SC_NPROCESSORS_ONLN );
    if (procs < 0)
    {
        perror( "sysconf" );
        return -1;
    }

    thrs = malloc( sizeof( pthread_t ) * procs );
    if (thrs == NULL)
    {
        perror( "malloc" );
        return -1;
    }

    printf( "Starting %d threads...\n", procs );
    for (i = 0; i < procs; i++)
    {
        if (pthread_create( &thrs[i], NULL, thread_routine,
        (void *)(long)i ))
        {
            perror( "pthread_create" );
            procs = i;
            break;
        }
    }

    for (i = 0; i < procs; i++)
        pthread_join( thrs[i], NULL );

    free( thrs );

    printf( "After doing all the math, global_int value is: %d\n",
    global_int );
    printf( "Expected value is: %d\n", INC_TO * procs );

    return 0;
}

 

 

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()