在Linux虚拟机中,用C语言实现多线程1+2+..+100000,并计算所需要的时间。
时间: 2024-05-09 18:20:20 浏览: 14
以下是一个简单的C语言程序,其中使用了pthread库来创建多个线程,每个线程都会打印出自己的线程号,然后累加1到100000的数字,最后将结果累加到共享变量sum中。
```c
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 10
#define MAX_NUM 100000
int sum = 0;
void *thread_func(void *arg) {
int thread_no = *(int *)arg;
int start = (thread_no - 1) * (MAX_NUM / NUM_THREADS) + 1;
int end = thread_no * (MAX_NUM / NUM_THREADS);
int i;
for (i = start; i <= end; i++) {
sum += i;
}
printf("Thread %d finished, sum = %d\n", thread_no, sum);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int i;
for (i = 0; i < NUM_THREADS; i++) {
thread_args[i] = i + 1;
pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("Total sum = %d\n", sum);
return 0;
}
```
在这个程序中,我们创建了10个线程(NUM_THREADS),每个线程都会执行thread_func函数。在主函数中,我们使用pthread_create函数创建了10个线程,并将每个线程的编号作为参数传递给thread_func函数。在thread_func函数中,我们根据线程编号计算出每个线程需要计算的数字范围,并将结果累加到共享变量sum中。在主函数中,我们使用pthread_join函数等待所有线程执行完毕,然后输出最终的结果sum。
为了计算程序的执行时间,我们可以使用time.h头文件中的clock函数。在程序的开头和结尾分别调用clock函数,然后计算两次调用之间的时间差来得到程序的执行时间。以下是修改后的程序:
```c
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 10
#define MAX_NUM 100000
int sum = 0;
void *thread_func(void *arg) {
int thread_no = *(int *)arg;
int start = (thread_no - 1) * (MAX_NUM / NUM_THREADS) + 1;
int end = thread_no * (MAX_NUM / NUM_THREADS);
int i;
for (i = start; i <= end; i++) {
sum += i;
}
printf("Thread %d finished, sum = %d\n", thread_no, sum);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int i;
clock_t start_time, end_time;
double total_time;
start_time = clock();
for (i = 0; i < NUM_THREADS; i++) {
thread_args[i] = i + 1;
pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
end_time = clock();
total_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
printf("Total sum = %d\n", sum);
printf("Total time = %f seconds\n", total_time);
return 0;
}
```
在程序的开头调用clock函数,记录下开始执行的时间;在程序的结尾再次调用clock函数,记录下结束执行的时间。然后计算两次调用之间的时间差,除以CLOCKS_PER_SEC得到程序的执行时间,以秒为单位。最后输出程序的执行时间。