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

时间:2021-08-19 15:12:45

I've wrote the following simple code and it should load 4 thread on CPU cores equally. but htop results shows that i have one thread with 100% CPU occupation and three threads with 25% CPU occupation. So i doubt that caller thread may have more load on CPU and i got confused. can anybody tell me the reason?

我已经编写了下面的简单代码,它应该同样地在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

2 个解决方案

#1


2  

The threads are either waiting for a lock on stderr in libc or they are all competing for the same lock in the operating system. Threads that wait for a lock won't use cpu. I'm surprised though that you have one thread using 100%. They should all be stuck waiting for a lock more or less equally.

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

#2


1  

I guess they might be waiting for a lock to get open so that next threads get executed

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

#1


2  

The threads are either waiting for a lock on stderr in libc or they are all competing for the same lock in the operating system. Threads that wait for a lock won't use cpu. I'm surprised though that you have one thread using 100%. They should all be stuck waiting for a lock more or less equally.

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

#2


1  

I guess they might be waiting for a lock to get open so that next threads get executed

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