cudaSetDevice和线程

1.cudaSetDevice是线程安全的

2.新创建的线程默认是device 0

 

#include <stdio.h>
#include <pthread.h>
#include <cuda.h>

#define N_THREAD 2

void *thread_run(void *pp)
{
    int *p=(int*)pp;
    
    int tid=p[0];
    int id;

    cudaGetDevice(&id);
    printf("%d idev=%d\n",tid,id);
    
    
    pthread_exit(NULL);
}

int main(int argc,char *argv[])
{
    pthread_t tid[2];
    int i;
    int ii[2];
    
    cudaSetDevice(1);
    
    for (i=0;i<N_THREAD;++i)
    {
        ii[i]=i;
        pthread_create(&tid[i],NULL,thread_run,&ii[i]);
    }
    
    for (i=0;i<N_THREAD;++i)
    {
        pthread_join(tid[i],NULL);
    }
    
}

运行截图

 

参考  http://devblogs.nvidia.com/parallelforall/cuda-pro-tip-always-set-current-device-avoid-multithreading-bugs/

posted on 2015-11-09 14:09  reedlau  阅读(7022)  评论(2编辑  收藏  举报

导航