Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这四个平行线程不';不能在cpu上均匀加载_C_Linux_Pthreads - Fatal编程技术网

为什么这四个平行线程不';不能在cpu上均匀加载

为什么这四个平行线程不';不能在cpu上均匀加载,c,linux,pthreads,C,Linux,Pthreads,我已经编写了以下简单代码,它应该在CPU内核上平均加载4个线程。但是htop结果显示,我有一个线程的CPU占用率为100%,三个线程的CPU占用率为25%。所以我怀疑调用线程可能会有更多的CPU负载,我感到困惑。有人能告诉我原因吗 #include <pthread.h> #include <stdio.h> void* print_ws( void* unused ) { while(1) fputc('W',stderr); retu

我已经编写了以下简单代码,它应该在CPU内核上平均加载4个线程。但是
htop
结果显示,我有一个线程的CPU占用率为100%,三个线程的CPU占用率为25%。所以我怀疑调用线程可能会有更多的CPU负载,我感到困惑。有人能告诉我原因吗

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

void* print_ws( void* unused )
{
    while(1)
        fputc('W',stderr);
    return NULL;
}//print_xs

void* print_zs( void* unused )
{
    while(1)
        fputc('Z',stderr);
    return NULL;
}//print_xs

void* print_xs( void* unused )
{
    while(1)
        fputc('X',stderr);
    return NULL;
}//print_xs

void* print_os( void* unused )
{
    while(1)    
        fputc('O',stderr);
    return NULL;
}

int main()
{
    pthread_t t1, t2, t3;
    // create a new thread. the new thread will run the print_xs
    pthread_create(&t1, NULL, &print_zs, NULL);
    pthread_create(&t2, NULL, &print_xs, NULL);
    pthread_create(&t3, NULL, &print_ws, NULL);
    print_os(NULL);
return 0;
}//main
#包括
#包括
作废*打印(作废*未使用)
{
而(1)
fputc(“W”,标准);
返回NULL;
}//打印
作废*打印(作废*未使用)
{
而(1)
fputc(“Z”,标准);
返回NULL;
}//打印
作废*打印(作废*未使用)
{
而(1)
fputc('X',标准偏差);
返回NULL;
}//打印
作废*打印操作系统(作废*未使用)
{
而(1)
fputc(“O”,标准);
返回NULL;
}
int main()
{
pthread_t t1、t2、t3;
//创建一个新线程。新线程将运行printxs
pthread_create(&t1,NULL,&print_zs,NULL);
pthread_create(&t2,NULL,&print_xs,NULL);
pthread_create(&t3,NULL,&print_ws,NULL);
打印操作系统(空);
返回0;
}//主要

线程要么正在等待libc中stderr上的锁,要么在操作系统中争夺同一个锁。等待锁定的线程不会使用cpu。我很惊讶,虽然你有一个线程使用100%。他们都应该或多或少地等待一个锁。

我猜他们可能是在等待一个锁打开,以便执行下一个线程

如果用一个简单的
替换每个
打印
例程中的
fputc
调用,会发生什么-即,如果您将每个线程例程设置为一个紧密的、硬编码的、牢不可破的循环?这将消除任何可能的锁争用。如果您尝试这样做,您可能只需要启动三个线程进行初始测试。分享和享受。在这里工作很好。我会说我观察到所有四个线程的负载均匀分布。我的问题是这是为了什么。我用两个线程做了一个测试。结果是惊人的。两个线程的CPU负载如下
pid:17984 CPU\u负载:100
pid:17985 CPU\u负载:50
,这意味着子线程的负载小于父线程。我不明白原因。