常用函数 | 功能 |
thread() |
构造一个线程对象,没有关联任何线程函数,即没有启动任何线程
|
get_id() | 获取线程id |
join() | 该函数调用后会阻塞住线程,当该线程结束后,主线程继续执行 |
detach() | 在创建线程对象后马上调用,用于把被创建线程与线程对象分离开,分离的线程变为后台线程,创建的线程的"死活"就与主线程无关 |
joinable() |
线程是否还在执行,joinable代表的是一个正在执行中的线程。
|
int main()
{
// 线程函数为函数指针
thread t1(ThreadFunc, 10);
// 线程函数为lambda表达式
thread t2([]{cout << "Thread2" << endl; });
// 线程函数为函数对象
TF tf;
thread t3(tf);
t1.join();
t2.join();
t3.join();
cout << "Main thread!" << endl;
return 0;
}
#include
using namespace std;
#include
unsigned long sum = 0L;
void fun(size_t num)
{
for (size_t i = 0; i < num; ++i)
sum++;
}
int main()
{
cout << "Before joining,sum = " << sum << std::endl;
thread t1(fun, 10000000);
thread t2(fun, 10000000);
t1.join();
t2.join();
cout << "After joining,sum = " << sum << std::endl;
return 0;
}
#include
using namespace std;
#include
#include
std::mutex m;
void fun(size_t num)
{
for (size_t i = 0; i < num; ++i)
{
m.lock();
sum++;
m.unlock();
}
}
#include
using namespace std;
#include
#include
atomic_long sum{ 0 };
void fun(size_t num)
{
for (size_t i = 0; i < num; ++i)
sum ++; // 原子操作
}
int main()
{
cout << "Before joining, sum = " << sum << std::endl;
thread t1(fun, 1000000);
thread t2(fun, 1000000);
t1.join();
t2.join();
cout << "After joining, sum = " << sum << std::endl;
return 0;
}
atmoic t; // 声明一个类型为T的原子类型变量t
常用函数名 | 函数功能 |
lock() |
上锁:锁住互斥量
|
unlock() |
解锁:释放对互斥量的所有权
|
try_lock() |
尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻
塞
|
template
class lock_guard
{
public:
// 在构造lock_gard时,_Mtx还没有被上锁
explicit lock_guard(_Mutex& _Mtx)
: _MyMutex(_Mtx)
{
_MyMutex.lock();
}
// 在构造lock_gard时,_Mtx已经被上锁,此处不需要再上锁
lock_guard(_Mutex& _Mtx, adopt_lock_t)
: _MyMutex(_Mtx)
{}
~lock_guard() _NOEXCEPT
{
_MyMutex.unlock();
}
lock_guard(const lock_guard&) = delete;
lock_guard& operator=(const lock_guard&) = delete;
private:
_Mutex& _MyMutex;
};
#include
#include
#include
void two_thread_print()
{
std::mutex mtx;
condition_variable c;
int n = 100;
bool flag = true;
thread t1([&](){
int i = 0;
while (i < n)
{
unique_lock lock(mtx);
c.wait(lock, [&]()->bool{return flag; });
cout << i << endl;
flag = false;
i += 2; // 偶数
c.notify_one();
}
}
});
thread t2([&](){
int j = 1;
while (j < n)
{
unique_lock lock(mtx);
c.wait(lock, [&]()->bool{return !flag; });
cout << j << endl;
j += 2; // 奇数
flag = true;
c.notify_one();
}
});
t1.join();
t2.join();
}
int main()
{
two_thread_print();
return 0;
}