1234567891011121314151617181920212223242526272829303132333435// C++98 实现的多线程,依赖第三方库 pthread#include <pthread.h>#include <iostream>using namespace std;static long long total = 0;pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;void* func(void*){ long long i; for (i = 0; i < 100000000L; ++i) { pthread_mutex_lock(&m); total += i; pthread_mutex_unlock(&m); } return NULL;}int main(){ pthread_t thread1, thread2; if (pthread_create(&thread1, NULL, &func, NULL)) { throw; } if (pthread_create(&thread2, NULL, &func, NULL)) { throw; } pthread_join(thread1, NULL); pthread_join(thread2, NULL); cout << total << endl; return 0;} 1234567891011121314151617181920212223242526// C++11 实现的多线程#include <atomic>#include <thread>#include <iostream>using namespace std;atomic_llong total{0};void func(int ){ for (long long i = 0; i < 100000000LL; ++i) { total += i; }}int main(){ thread t1(func, 0); thread t2(func ,0); t1.join(); t2.join(); cout << total << endl; return 0;}