minclude #include astolib…ha #include sothread.ha int sumi = 0, sum2 = void p1() ( int 1, tmp = 0; for (i = 1: 1 <= 100; 1++) tmp += i; sum1 += tmp; void +p2() ( int for (i I ioi, ': « 200; tmp += i; sum2 tmp; void 030)4 printf ("sum: sdin't sumi sum2) int main() f int res; pthread t pthread t t2; void thread result; res - pthread create(Stl, NULL, p1, NULL) if (res = 0). perror ("failed to create thread"): exit (1): res = pthread create (St2, NULL, p2, NULL): if tres 1= 910 perrori failed to join thread" )exit (2): res res p30): return. 0: othread join(tl.&thread result) pthread join (t2,&thread result),纠正此代码
时间: 2023-08-22 12:07:49 浏览: 247
sumi:从 code.google.compsumi 自动导出
以下是经过纠正的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *p1(void *arg) {
int i, tmp = 0;
for (i = 1; i <= 100; i++) {
tmp += i;
}
*(int *)arg += tmp;
return NULL;
}
void *p2(void *arg) {
int i, tmp = 0;
for (i = 101; i <= 200; i++) {
tmp += i;
}
*(int *)arg += tmp;
return NULL;
}
int main() {
int sum1 = 0, sum2 = 0;
pthread_t t1, t2;
void *result;
int res = pthread_create(&t1, NULL, p1, &sum1);
if (res != 0) {
perror("failed to create thread");
exit(1);
}
res = pthread_create(&t2, NULL, p2, &sum2);
if (res != 0) {
perror("failed to create thread");
exit(1);
}
res = pthread_join(t1, &result);
if (res != 0) {
perror("failed to join thread");
exit(2);
}
res = pthread_join(t2, &result);
if (res != 0) {
perror("failed to join thread");
exit(2);
}
printf("sum: %d %d\n", sum1, sum2);
return 0;
}
这段代码的功能是创建两个线程,分别计算1到100和101到200的整数的和,然后将两个和输出。在主函数中,先创建两个线程并分别执行p1和p2函数,将计算结果存储在sum1和sum2变量中。然后通过pthread_join函数等待线程执行完毕,并将结果存储在result变量中。最后将两个和输出。
阅读全文