1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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;
}