c++マルチスレッドの作成の3つの方法
16042 ワード
c++11以降はマルチスレッドプログラミングがサポートされる.C++11ではstd::threadオブジェクトを作成することで、新しいスレッドを作成できます.各std::threadオブジェクトは、1つのスレッドに関連付けることができます.
std::threadオブジェクトに関数を追加します.
関数ポインタを使用したスレッドの作成
関数オブジェクトを使用したスレッドの作成
Lambda関数を使用したスレッドの作成
スレッドの各stdを区別する方法::threadオブジェクトにはIDがあり、次の関数を使用して取得できます.
現在のスレッドのIDを取得するには、次の手順に従います.
std::threadオブジェクトに関数を追加します.
std::thread thObj();
というコールバック関数は、この新しいスレッドの起動時に実行されます.これらのコールバックは、1、関数ポインタ2、関数オブジェクト3、Lambda関数関数ポインタを使用したスレッドの作成
#include
#include
using namespace std;
void thread_function()
{
for (int i = 0; i < 10; i++)
{
cout << "Thread function executing!" << endl;
}
}
int main()
{
std::thread threadObj(thread_function);
for (int i = 0; i < 10; i++)
{
cout << "MainThread executing!" << endl;
}
threadObj.join();// ,
cout << "EXIT!!" << endl;
system("pause");
return 0;
}
関数オブジェクトを使用したスレッドの作成
#include
#include
using namespace std;
class DisplayThread
{
public:
void operator()()
{
for (int i = 0; i < 10; i++)
{
cout << "Thread function executing!" << endl;
}
}
};
int main()
{
thread threadObj((DisplayThread()));
for (int i = 0; i < 10; i++)
{
cout << "MainThread executing!" << endl;
}
threadObj.join();// ,
cout << "EXIT!!" << endl;
system("pause");
return 0;
}
Lambda関数を使用したスレッドの作成
#include
#include
using namespace std;
int main()
{
thread threadObj([] {
for (int i = 0; i < 10; i++)
{
cout << "Thread function executing!" << endl;
}});
for (int i = 0; i < 10; i++)
{
cout << "MainThread executing!" << endl;
}
threadObj.join();// ,
cout << "EXIT!!" << endl;
system("pause");
return 0;
}
スレッドの各stdを区別する方法::threadオブジェクトにはIDがあり、次の関数を使用して取得できます.
std::thread::get_id()
現在のスレッドのIDを取得するには、次の手順に従います.
std::this_thread::get_id()
#include
#include
using namespace std;
void thread_function()
{
cout << "Inside Thread :: ID = " << this_thread::get_id() << endl;
}
int main()
{
thread threadObj1(thread_function);
thread threadObj2(thread_function);
if (threadObj1.get_id() != threadObj2.get_id())
{
cout << "Both Threads have different IDs!" << endl;
}
cout << "From main Thread :: ID of threadObj1 is " << threadObj1.get_id() << endl;
cout << "From main Thread :: ID of threadObj2 is " << threadObj2.get_id() << endl;
threadObj1.join();
threadObj2.join();// ,
cout << "EXIT!!" << endl;
system("pause");
return 0;
}