使用 pthreads 创建多个线程的问题

Issue creating multiple threads with pthreads

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


void *compute() {

float total;
int i;
float oldtotal =0, result =0;

for(i=0;i<1999999999;i++)
{
    result =sqrt(1001.0)*sqrt(1001.0);  
}

printf ("Result is %f\n", result);
oldtotal = total;
total = oldtotal + result;

printf("Total is %f\n",total);

return NULL;


}


int main() {


pthread_t thread1, thread2;

pthread_create(&thread1, NULL,compute, NULL); 

pthread_create(&thread2, NULL,compute, NULL); 


pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

return 0;
}

我运行程序只创建了一个线程。我已经使用 cmd 中的 top 命令检查了这一点,进程 运行s 在 197%,所以我相信两个进程正在 运行。我记得用 -pthreads 标志编译它。

197% = 2 个线程在一个循环中执行 cpu 做 sqrt(),加上一个没有使用任何 cpu 的线程,因为它正在等待其他线程完成在 pthread_join().