c++11 thread 类内使用方法和跨类使用方法
来源:互联网 发布:网络攻防基础题库 编辑:程序博客网 时间:2024/06/04 23:19
忘了为啥之前查的用上bind了,把项目搞完之后终于有时间建个小工程仔细试下怎么用。
Case 1 : 根据类内函数创建thread
class A
{
public:
A();
~A();
{
public:
A();
~A();
void run(int i) {
cout << i << endl;
}
cout << i << endl;
}
void thread_run() {
for (int i = 0; i < 5; ++i) {
thread t(&A::run, this, i);
t.join();
}
}
};
for (int i = 0; i < 5; ++i) {
thread t(&A::run, this, i);
t.join();
}
}
};
int main() {
A a;
a.thread_run();
return 0;
}
Case 2 : 在类外根据某一个类的函数创建thread
class A
{
public:
A();
~A();
{
public:
A();
~A();
void run(int i) {
cout << i << endl;
}
cout << i << endl;
}
};
int main() {
A a;
for (int i = 0; i < 5; ++i) {
thread t(&A::run, &a, i);
t.join();
}
return 0;
}
Case 3 : 在一个类中根据另一个类的函数创建thread
class A
{
public:
A();
~A();
{
public:
A();
~A();
void run(int i) {
cout << i << endl;
}
cout << i << endl;
}
};
class B
{
public:
B();
~B();
{
public:
B();
~B();
void run() {
A a;
for (int i = 0; i < 1000; ++i) {
thre.fdad t(&A::run, &a, i);
A a;
for (int i = 0; i < 1000; ++i) {
thre.fdad t(&A::run, &a, i);
t.join();
}
}
};
}
}
};
int main() {
A a;
B b;
b.run();
B b;
b.run();
return 0;
}
}
居然都是完全没问题的!!!我就奇怪了当初在工程里为毛怎么都不行。
注意点大概如下:
1. thread的第一个参数一定是 &类名::函数名 的形式
2. thread的第二个参数一定是类实例的指针
3. thread的之后的参数是函数所需要的参数
另外这样for循环创建的thread一定是执行完一个线程才创建下一个线程的,如果想要线程一起创建,需要先用一个vector把创建的thread存起来(千万不能直接存实例,因为vector在push_back时会再次构造),之后再一个for循环一起join;或者直接把join改成detach。
比较坑的地方可能就是thread传入类的函数和全局函数或者static函数时,参数是有区别的(后两个不需要类实例的指针),可能就是因为这个才让我当初怎么搞都没搞通吧。
阅读全文
0 0
- c++11 thread 类内使用方法和跨类使用方法
- java之多线程中Thread类和Runnable接口使用方法
- Runnable类使用方法+与Thread区别
- C++ 类的内建函数使用方法
- 嵌套类,内部类,匿名内部类的定义和使用方法
- [C#] DataRow类的使用方法
- [C#] DataRow类的使用方法
- boost::thread使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- Thread 的使用方法
- android thread Interrupte使用方法
- HandlerThread,Handler,Thread使用方法
- HandlerThread,Handler,Thread使用方法
- python字符串连接的三种方法及其效率、适用场景详解
- unity--3D物体的上下左右移动,鼠标控制大小,旋转
- Windows下安装Redis教程
- android studio 更新3.0后多渠道打包配置问题
- Retrofit2
- c++11 thread 类内使用方法和跨类使用方法
- synchronized同步三种使用方法
- Java基础知识:循环(1)
- CSS优先级
- html 内联类型容器中文本溢出部分隐藏
- 过滤器监听器JavaBean
- 数值的扩展
- Assignment | 01-week1-Introduction to deep learning
- 剑指offer 编程题(30):自然数中出现1的次数