如何正确使用PTHREAD_SETAFFINITY_NP?

时间:2014-07-30 08:37:42

标签: multithreading concurrency pthreads

我正在研究一个基于大量数据进行计算的程序。所以我创建了两个线程。他们的工作相似,但他们的数据不同。我使用以下代码执行此操作:

status1 = pthread_create(&pthread1,NULL,func_1,(void*)t1);
if(status1 != 0)
    printf("pthread1 is not created sucessfully!\n");
status = pthread_create(&pthread2,NULL,func_2,(void*)t2);
if(status != 0)
    printf("pthread2 is not created successfully!\n");

func_1和func_2类似。 然后我想将它们发送到不同的处理器。所以我使用PTHREAD_SETAFFINITY_NP,但它失败了。 我的代码如下。

void func_1()
{
    cpu_set_t mask1;
    CPU_ZERO(&mask1);
    CPU_SET(1,&mask1);
    pthread_setaffinity_np(pthread_self(),sizeof(mask1),&mask1);
    for (j = 0; j < cpu_num; j++) {
    if (CPU_ISSET(j, &mask1)) 
    {
        //printf("thread %lld is running in processor %d\n", pthread_self(), j);
         cout<<"thread "<<pthread_self()<<" is running in processor "<< j <<endl;
    }
}
void func_2()
{
    cpu_set_t mask2;
    CPU_ZERO(&mask2);
    CPU_SET(0,&mask2);
    pthread_setaffinity_np(pthread_self(),sizeof(mask2),&mask2);
    for (j = 0; j < cpu_num; j++) {
    if (CPU_ISSET(j, &mask2)) 
    {
        //printf("thread %lld is running in processor %d\n", pthread_self(), j);
         cout<<"thread "<<pthread_self()<<" is running in processor "<< j <<endl;
    }
}

int main()
{
    status1 = pthread_create(&pthread1,NULL,func_1,(void*)t1);
    if(status1 != 0)
        printf("pthread1 is not created sucessfully!\n");
    status = pthread_create(&pthread2,NULL,func_2,(void*)t2);
    if(status != 0)
        printf("pthread2 is not created successfully!\n");
    pthread_join(pthread1,NULL);
    pthread_join(pthread2,NULL);
    ......
}

但令我惊讶的是,结果如下:

thread 7369190208 is running in processor 0
thread 3065830208 is running in processor 0

如何将每个线程分派到特定的处理器?

编辑: 我想将线程分配到不同的处理器,因为如果它们在一个处理器上运行,它就像是serial.How如何发送?如下所示: 串行:     for(i = 0; i&lt; N; i ++)         做一点事; 我使用两个线程,然后它变成了:

pthread1:

for(i = 0 ; i < N ; i += 2)
    do something;

pthread2:

for(i = 1 ; i < N ; i += 2)
    do something;

并且加速可能接近2

0 个答案:

没有答案