对于下面的代码,我的 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/