多个线程导致更多的CPU使用率

0 c linux

对于下面的代码,我的cpu使用率是97%.我在Ubuntu上运行c代码.

#include <stdio.h>
#include<pthread.h>
void *s_thread(void *x)
{
        printf("I am in first thread\n");
} 
void *f_thread(void *x)    
{
        printf("I am in second thread\n");
}

int main()
{
        printf("I am in main\n");
        pthread_t fth;
        int ret;
        ret = pthread_create( &fth,NULL,f_thread,NULL);
        ret = pthread_create( &sth,NULL,s_thread,NULL); 
        while(1);
        return 0;
}        
Run Code Online (Sandbox Code Playgroud)

这个简单的代码比仅运行一个线程给我更多的CPU使用率.

Mun*_*tap 6

int main()
{
    printf("I am in main\n");

    pthread_t fth,sth;
    int ret;

    ret = pthread_create( &fth,NULL,f_thread,NULL);
    ret = pthread_create( &sth,NULL,s_thread,NULL); 

    pthread_join(&fth,NULL);
    pthread_join(&sth,NULL);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

while(1)使用更多的CPU周期,因此使用pthread_join并加入进程,以便main线程等待子线程完成.