FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpp/Multithreading/problems/synchronize-two-threads.cpp at master-cpp · 1aman1/cpp · GitHub
1aman1
/
cpp
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
0
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpp
/
Multithreading
/
problems
/
synchronize-two-threads.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
54 lines (47 loc) · 1.12 KB
Breadcrumbs
cpp
/
Multithreading
/
problems
/
synchronize-two-threads.cpp
Copy path
File metadata and controls
54 lines (47 loc) · 1.12 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#
include
<
iostream
>
#
include
<
mutex
>
#
include
<
thread
>
#
include
<
condition_variable
>
class
ThreadNNeedle
{
std::condition_variable cv;
std::mutex mutex;
int
flag =
1
;
const
int
RANGE
=
10
;
public:
void
thread1
()
{
for
(
int
i =
0
; i <
RANGE
; i +=
2
)
{
std::unique_lock<std::mutex>
lock
(mutex);
cv.
wait
(lock,
[
this
]
{
return
flag &
1
?
1
:
0
; });
std::cout <<
"
thread 1:
"
<< flag++ << std::endl;
lock.
unlock
();
cv.
notify_one
();
}
}
void
thread2
()
{
for
(
int
i =
1
; i <
RANGE
; i +=
2
)
{
std::unique_lock<std::mutex>
lock
(mutex);
cv.
wait
(lock,
[
this
]
{
return
flag &
1
?
0
:
1
; });
std::cout <<
"
thread 2:
"
<< flag++ << std::endl;
lock.
unlock
();
cv.
notify_one
();
}
}
};
int
main
()
{
ThreadNNeedle obj;
std::thread
t1
(&ThreadNNeedle::thread1, &obj);
std::thread
t2
(&ThreadNNeedle::thread2, &obj);
t1.
join
();
t2.
join
();
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL