thread
创建一个简单线程
#include
#include
#include
#include
void f1(int n)
{
for (int i=0;i<5;i++)
{
std::cout << "Thread 1 executingn";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void f2(int& n)
{
for (int i=0;i<5;i++)
{
std::cout << "Thread 2 executingn";
++n;
//Blocks the execution of the current thread for at least the specified sleep_duration
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main()
{
int n = 1;
std::thread t1(f1,10);
std::thread t2(f2,std::ref(n));
std::thread::id t1_id = t1.get_id();
std::thread::id t2_id = t2.get_id();
std::cout << "t1's id: " << t1_id << 'n';
std::cout << "t2's id: " << t2_id << 'n';
t1.join(); // waits for the thread to finish its execution
t2.join();
std::cout << "now n = " << n << std::endl;
}
// g++ thread.cpp -o thread -Wall -g -lpthread
mutex
mutex是用来保证线程同步的,防止不同的线程同时操作同一个共享数据
#include
#include
#include
#include