34 lines
750 B
C
34 lines
750 B
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <pthread.h>
|
|
#include <string.h>
|
|
|
|
long ans = 0;
|
|
pthread_mutex_t lock;
|
|
|
|
void* calc(void* args) {
|
|
int sec = *(int*)args;
|
|
int p_ans = 0;
|
|
for(int i = sec * 250000; i < (sec + 1) * 250000; i++) {
|
|
p_ans += i;
|
|
}
|
|
pthread_mutex_lock(&lock);
|
|
ans += p_ans;
|
|
pthread_mutex_unlock(&lock);
|
|
return NULL;
|
|
}
|
|
|
|
int main() {
|
|
pthread_t thread[4];
|
|
pthread_mutex_init(&lock, NULL);
|
|
int arr[4] = {0, 1, 2, 3};
|
|
for (int i = 0; i < 4; i++) {
|
|
pthread_create(&thread[i], NULL, calc, &arr[i]);
|
|
}
|
|
for (int i = 0; i < 4; i++) {
|
|
pthread_join(thread[i], NULL);
|
|
}
|
|
printf("Final answer: %d\n", ans);
|
|
pthread_mutex_destroy(&lock);
|
|
return 0;
|
|
} |