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

时间:2015-03-06 13:02:04

标签: c linux multithreading ubuntu 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命令检查了这个,进程运行在197%,所以我相信正在运行两个进程。我记得用-pthreads标志编译它。

1 个答案:

答案 0 :(得分:0)

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

相关问题