-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path27.atomic.cpp
More file actions
102 lines (85 loc) · 1.73 KB
/
Copy path27.atomic.cpp
File metadata and controls
102 lines (85 loc) · 1.73 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// Created by satellite on 20/05/2023.
//
//#define code_6_18
//#define code_6_19
//#define code_6_20
#ifdef code_6_18
#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<100000000LL;i++){
pthread_mutex_lock(&m);
total+=i;
pthread_mutex_unlock(&m);
}
}
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;//9999999900000000
return 0;
}
#endif
#ifdef code_6_19
#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;//9999999900000000
return 0;
}
#endif
#ifdef code_6_20
#include <thread>
#include <atomic>
#include <iostream>
#include <unistd.h>
using namespace std;
std::atomic_flag lock=ATOMIC_FLAG_INIT;
void f(int n){
while(lock.test_and_set(std::memory_order_acquire))//尝试获得锁
cout<<"Waiting from thread"<<n<<endl;//自旋
cout<<"Thread"<<n<<"starts working"<<endl;
}
void g(int n){
cout<<"Thread"<<n<<"is going to start."<<endl;
lock.clear();
cout<<"Thread"<<n<<"starts working"<<endl;
}
int main(){
lock.test_and_set();
thread t1(f,1);
thread t2(g,2);
t1.join();
usleep(100);
t2.join();
}
#endif
#include "vector"
int main()
{
std::vector<int> vi;
}