Date 2015/11/05 Ddd By WJB
上一次编写了一个最简单的多线程程序,这次介绍一种新的创建线程的方法和一些基本操作;
(上一篇文章连接:https://blog.youkuaiyun.com/wangjianbo09/article/details/80028515)
1,void operator()():The first () is the name of the operator - it's the operator that is invoked when you use () on the object. The second () is for the parameters, of which there are none.
第一个()是操作符的名字, 当对象前面用()时,()的操作将被调用;第二个()用于参数的传入,多用在多线程中。
实例:
class background_task
{
public:
void operator()() const
{
do_something();
do_something_else();
}
};
background_task task;
task();
示例中传入参数为空。
2,void operator()()在多线程中的应用
class fctor
{
public:
void operator()()
{
for (int i =0;i<100;i++)
{
std::cout << "mythread:" << i << std::endl;
}
}
};
thread mythread1((fctor()));
mythread.join();
//需要传入参数,但参数是拷贝
class fctor2
{
public:
void operator()(std::string msg )
{
for (int i = 0; i < 100; i++)
{
cout << "fctor2"<<msg << endl;
}
}
};
thread mythread2((fctor2()),"I Love You!");
mythread2.join();
//需要传入参数,以引用的方式传入参数
class fctor3
{
public:
void operator()(std::string &msg)
{
cout << "fctor3 thread ID:" << std::this_thread::get_id() << endl; //输出当前线程ID
cout << "fctor2" << msg << endl;
msg = "I love you too;";
}
};
std::string str = "I Love You!";
//thread mythread3((fctor3()),std::ref(str));//这种防暑传入参数会造成内存竞争,修改为move
thread mythread3((fctor3()), std::move(str));
3,多线程中的基本操作
- 获取当前线程 :std::this_thread::get_id() ;
- 获取当点硬件支持的最大线程数:std::thread::hardware_concurrency()
4,全部代码(vs2015 win32控制台程序)main.cpp
#include <thread>
#include <iostream>
#include <string>
using namespace std;
void Function_1()
{
printf("my name is multithread!");
}
class fctor
{
public:
void operator()()
{
for (int i =0;i<100;i++)
{
cout << "mythread:" << i << endl;
}
}
};
//需要传入参数,但参数是拷贝
class fctor2
{
public:
void operator()(std::string msg )
{
for (int i = 0; i < 100; i++)
{
cout << "fctor2"<<msg << endl;
}
}
};
//需要传入参数,以引用的方式传入参数
class fctor3
{
public:
void operator()(std::string &msg)
{
cout << "fctor3 thread ID:" << std::this_thread::get_id() << endl; //输出当前线程ID
cout << "fctor2" << msg << endl;
msg = "I love you too;";
}
};
int main()
{
fctor ftr;
//thread mythread(ftr); //两周调用方式等价
//thread mythread1((fctor())); //两周调用方式等价
// 如果想传入参数如下
//thread mythread2((fctor2()),"I Love You!");
std::string str = "I Love You!";
//thread mythread3((fctor3()),std::ref(str));//这种防暑传入参数会造成内存竞争,修改为move
thread mythread3((fctor3()), std::move(str));
mythread3.join();
cout << "from main:" << str << endl;
cout << "from main thread ID:" << std::this_thread::get_id() << endl; //输出当前线程ID
cout << "hardware thread max:" << std::thread::hardware_concurrency() << endl; //输出当前线程ID
//mythread.join(); //阻塞式
//mythread1.join();
//mythread2.join();
// 非阻塞式
//mythread.detach();
return 0;
}