Linux上的PThreads和MultiCore CPU

IRT*_*HUS 13 c c++ linux pthreads

我正在编写一个使用Threads来提高性能的简单应用程序.问题是,这个应用程序在Windows上运行正常,使用我的CPU拥有的2个内核.但是当我在Linux上执行时,似乎只使用了1个Core.

我不明白为什么会这样.

这些是我的代码,C++:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>

void* function(void*)
{
    int i=0;
    for(i=0; i<1110111; i++)
        rand();
    return 0;
}

void withOutThreads(void)
{
    function(0);
    function(0);
}

void withThreads(void)
{
    pthread_t* h1 = new pthread_t;
    pthread_t* h2 = new pthread_t;
    pthread_attr_t* atr = new pthread_attr_t;

    pthread_attr_init(atr);
    pthread_attr_setscope(atr,PTHREAD_SCOPE_SYSTEM);

    pthread_create(h1,atr,function,0);
    pthread_create(h2,atr,function,0);

    pthread_join(*h1,0);
    pthread_join(*h2,0);
    pthread_attr_destroy(atr);
    delete h1;
    delete h2;
    delete atr;
}

int main(void)
{
    int ini,tim;
    ini = clock();
    withOutThreads();
    tim = (int) ( 1000*(clock()-ini)/CLOCKS_PER_SEC );
    printf("Time Sequential: %d ms\n",tim);
    fflush(stdout);

    ini = clock();
    withThreads();
    tim = (int) ( 1000*(clock()-ini)/CLOCKS_PER_SEC );
    printf("Time Concurrent: %d ms\n",tim);
    fflush(stdout);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Linux上的输出:

Time Sequential: 50 ms
Time Concurrent: 1610 ms
Run Code Online (Sandbox Code Playgroud)

Windows上的输出:

Time Sequential: 50 ms
Time Concurrent: 30 ms
Run Code Online (Sandbox Code Playgroud)

nos*_*nos 19

clock()在windows vs linux上的工作方式不同,所以不要用它来测量时间.在linux上它测量CPU时间,在Windows上它测量挂钟时间.理想情况下,在这个测试用例中这些是相同的,但是你应该使用平台之间的某些东西来测量时间.例如gettimeofday()

rand()在linux上序列化你的线程.rand()拥有一个内部锁,以确保线程安全.rand()管理页面状态rand()不是线程安全的,也不是可重入的,但至少最近的glibc中的代码需要锁定调用.我不确定windows如何处理它,或者它根本不是线程安全的,或者它使用线程局部变量.

在linux上使用rand_r,或者找一些更好的CPU利用率来测量.

void* function(void*)
{
    unsigned int seed = 42;
    int i=0;
    for(i=0; i<1110111; i++)
        rand_r(&seed);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 当它在Linux上测量CPU时间时,它会在程序中的所有线程中测量它. (4认同)

Max*_*kin 8

问题是Linux多线程版本或rand()锁定互斥锁.将您的功能更改为:

void* function(void*)
{
    int i=0;
    unsigned rand_state = 0;
    for(i=0; i<1110111; i++)
        rand_r(&rand_state);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Time Sequential: 10 ms
Time Concurrent: 10 ms
Run Code Online (Sandbox Code Playgroud)