Multithreading 如何正确使用PTHREAD_SETAFFINITY_NP?

Multithreading 如何正确使用PTHREAD_SETAFFINITY_NP?,multithreading,concurrency,pthreads,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*)t

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

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);
    ......
}
如何将每个线程分派到特定的处理器

编辑: 我想将线程分派到不同的处理器,因为如果两个线程在一个处理器上运行,这就像串行。如何分派?如下所示: 序列号: 对于(i=0;i pthread1:

for(i = 0 ; i < N ; i += 2)
    do something;
(i=0;i 做点什么; pthread2:

for(i = 1 ; i < N ; i += 2)
    do something;
(i=1;i 做点什么;
的加速比可以接近2

您的
printf
假设
pthread\u t
long
相同。如果不是这样,您将得到未定义的行为。您的意思是
printf(“线程%lld正在处理器%d\n中运行”,pthread_self(),j)?pthread_self()返回线程的id,它是
long
,是吗?也许我还不明白你的意思,但困扰我的是找出是什么原因导致了我的错误发送。:)类型是
pthread\u t
,这是您的操作系统定义的类型(
unsigned long
在我的上,您的可能不同)。或者将其转换为与
printf
说明符匹配的已知类型,或者(因为您已经标记了问题C++)使用类型安全
cout
。哦,我理解,谢谢。您能帮我解决另一个问题吗?(我会纠正它)
for(i = 1 ; i < N ; i += 2)
    do something;