c - 多个线程导致更多 CPU 使用

标签 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;
}        

这个简单的代码比只运行一个线程给我更多的 cpu 使用率。

最佳答案

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;
}

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

关于c - 多个线程导致更多 CPU 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252580/

相关文章:

c - C中的MPI前缀和

c - 在c中分配内存时写入、读取无效

c - Linux,C : threads synch

android - grep 精确匹配

linux - 如何在 Unix 中 grep 两个日期范围之间的日志

node.js - 将环境变量传递给 pm2 不起作用

c - 通过代码动态写入文件名-C

计算 Midi Sample Dump Standard 数据包的校验和

linux - 日期中的时区?

c - 宏观协议(protocol)中的错误、分歧