Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
C
cpp_parallelism
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Model registry
Operate
Environments
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Erik Strand
cpp_parallelism
Commits
af6fa97b
Commit
af6fa97b
authored
6 years ago
by
Erik Strand
Browse files
Options
Downloads
Patches
Plain Diff
Add mutex example
parent
7c15bf3d
No related branches found
No related tags found
No related merge requests found
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
mutex.cpp
+26
-0
26 additions, 0 deletions
mutex.cpp
thread.cpp
+2
-1
2 additions, 1 deletion
thread.cpp
with
28 additions
and
1 deletion
mutex.cpp
0 → 100644
+
26
−
0
View file @
af6fa97b
#include
<array>
#include
<thread>
#include
<iostream>
int
main
()
{
constexpr
auto
n_threads
=
10u
;
std
::
array
<
std
::
thread
,
n_threads
>
threads
;
std
::
mutex
cout_mutex
;
const
auto
hello
=
[
&
cout_mutex
](
int
i
)
{
// Uncommenting this line will randomly interleave all the threads' outputs.
std
::
lock_guard
<
std
::
mutex
>
cout_lock
(
cout_mutex
);
std
::
cout
<<
"Hello from thread "
<<
i
<<
'\n'
;
};
for
(
auto
i
=
0u
;
i
<
n_threads
;
++
i
)
{
threads
[
i
]
=
std
::
thread
(
hello
,
i
);
}
for
(
auto
i
=
0u
;
i
<
n_threads
;
++
i
)
{
threads
[
i
].
join
();
}
return
0
;
}
This diff is collapsed.
Click to expand it.
thread.cpp
+
2
−
1
View file @
af6fa97b
...
...
@@ -13,7 +13,8 @@ struct ThreadObject {
int
main
()
{
// Note that no care is taken to avoid race conditions around the global object std::cout.
// Arguments are copied into the child threads.
// See mutex.cpp for a solution.
// Note that arguments are passed by value to the child threads.
auto
function_thread
=
std
::
thread
(
thread_method
,
1
);
auto
object_thread
=
std
::
thread
(
ThreadObject
(),
2
);
auto
lambda_thread
=
std
::
thread
([](
int
i
)
{
...
...
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment