Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
48b5a4cc
Commit
48b5a4cc
authored
Nov 28, 2022
by
Administrator
Browse files
add thread
parent
f0334279
Changes
1
Hide whitespace changes
Inline
Side-by-side
03.Advanced/Thread.cpp
0 → 100644
View file @
48b5a4cc
#include <iostream>
#include <thread>
using
namespace
std
;
// 定义用于用法1的函数
void
foo
(
int
tid
,
string
name
)
{
string
msg
;
msg
=
"Thread "
+
to_string
(
tid
)
+
" starting
\n
"
;
cout
<<
msg
;
for
(
int
i
=
0
;
i
<
10
;
i
++
)
{
msg
=
"Hello from foo "
+
to_string
(
tid
)
+
":"
+
name
+
":"
+
to_string
(
i
)
+
" ending
\n
"
;
cout
<<
msg
;
}
msg
=
"Thread "
+
to_string
(
tid
)
+
" ending
\n
"
;
cout
<<
msg
;
};
// 定义用于用法2的函数对象
class
func_obj_class
{
public:
// ()操作符重载
void
operator
()
(
int
tid
,
string
name
)
{
string
msg
;
msg
=
"Thread "
+
to_string
(
tid
)
+
" starting
\n
"
;
cout
<<
msg
;
for
(
int
i
=
0
;
i
<
10
;
i
++
)
{
msg
=
"Hello from func_obj_class "
+
to_string
(
tid
)
+
":"
+
name
+
":"
+
to_string
(
i
)
+
" ending
\n
"
;
cout
<<
msg
;
}
msg
=
"Thread "
+
to_string
(
tid
)
+
" ending
\n
"
;
cout
<<
msg
;
}
};
int
main
()
{
cout
<<
thread
::
hardware_concurrency
()
<<
endl
;
// 用法1: 通过指定函数名(函数指针),启动线程
thread
func_t0
(
foo
,
0
,
"first"
);
thread
func_t1
(
foo
,
1
,
"second"
);
// 用法2: 通过指定函数对象,启动线程
thread
obj_t0
(
func_obj_class
(),
2
,
"third"
);
// 用法3: 通过Lambda表达式,启动线程
// 定义Lambda表达式
auto
f
=
[]
(
int
tid
,
string
name
)
{
string
msg
;
msg
=
"Thread "
+
to_string
(
tid
)
+
" starting
\n
"
;
cout
<<
msg
;
for
(
int
i
=
0
;
i
<
10
;
i
++
)
{
msg
=
"Hello from auto_f "
+
to_string
(
tid
)
+
":"
+
name
+
":"
+
to_string
(
i
)
+
" ending
\n
"
;
cout
<<
msg
;
}
msg
=
"Thread "
+
to_string
(
tid
)
+
" ending
\n
"
;
cout
<<
msg
;
};
// 使用Lambda表达式启动线程
thread
auto_f_t0
(
f
,
3
,
"fourth"
);
// 等待所有线程结束
func_t0
.
join
();
func_t1
.
join
();
obj_t0
.
join
();
auto_f_t0
.
join
();
cout
<<
"main() exiting"
<<
endl
;
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment