【问题标题】:Issue creating multiple threads with pthreads使用 pthreads 创建多个线程的问题
【发布时间】:2015-03-06 13:02:04
【问题描述】:
#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 标志编译它。

【问题讨论】:

  • 你怎么知道“只创建了一个线程”?
  • 如果进程以超过 100% 的速度运行,那么您肯定有多个线程。默认情况下,top 命令不只显示线程进程。
  • 如何将其拆分以显示多个进程?
  • 我对这个问题以及存在任何“问题”的论点提出异议。

标签: c linux multithreading ubuntu pthreads


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2013-02-08
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多