出道题+送点分+混脸熟
以下代码运行的结果是什么?为什么?
// chance_to_see_99.cpp
// g++ -g -pthread chance_to_see_99.cpp -lpthread -o chance_to_see_99
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
const int number_of_threads = 100;
int global_sum = 0;
void *increment_fn(void *arg) {
++global_sum;
return (void *)0;
}
int main() {
pthread_t thread_ids[number_of_threads] = { 0 };
for (int index = 0; index != number_of_threads; ++index) {
int create_thread_result = pthread_create(
&thread_ids[index], NULL, increment_fn, NULL);
if (create_thread_result != 0) {
printf("create thread fail. index: %d\n", index);
return EXIT_FAILURE;
}
}
for (int index = 0; index != number_of_threads; ++index) {
int join_thread_result = pthread_join(
thread_ids[index], NULL);
if (join_thread_result != 0) {
printf("join thread fail. index: %d\n", index);
return EXIT_FAILURE;
}
}
printf("global_sum: %d\n", global_sum);
return EXIT_SUCCESS;
}