对于低于我的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/