Расчёт суммы чисел в два потока на отрезке от 1 до 2000.
Первый поток считает сумму от 1 до 1000.
Второй поток считает сумму от 1001 до 2000.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <pthread.h>
using namespace std;
int a1, b1, s1;
int a2, b2, s2;
void longFunction() {
for(int k = 0; k < 10000000; k++) {
int h = 1;
h *= 2;
h *= 3;
h *= 4;
}
}
void * first(void *) {
s1 = 0;
for(int i = a1; i <= b1; i++) {
cout << "A";
s1 += i;
longFunction();
}
}
void * second(void *) {
s2 = 0;
for(int i = a2; i <= b2; i++) {
cout << "a";
s2 += i;
longFunction();
}
}
int main() {
a1 = 1;
b1 = 1000;
a2 = 1001;
b2 = 2000;
cout << "\n\n";
pthread_t x1;
pthread_t x2;
// run First thread
pthread_create(&x1, NULL, first, NULL);
// run Second thread
pthread_create(&x2, NULL, second, NULL);
// wait finish of First thread
pthread_join(x1, NULL);
// wait finish of Second thread
pthread_join(x2, NULL);
cout << "\n\n";
cout << "S1 = " << s1 << "\n";
cout << "S2 = " << s2 << "\n";
cout << "S1 + S2 = " << (s1 + s2) << "\n\n";
cout << "Time: " << clock() << "\n\n";
return 0;
}