贡献者: addis
std::thread
底层通常使用 pthread。
#include <thread>
,#include <mutex>
std::thread th(函数, arg1, arg2, ...)
; 创建一个线程,调用 函数
(可以是函数指针,函数对象,lambda),arg
是 函数
的变量。
th.join()
可以让主程序等待某个线程自己退出。
std::mutex m
相当于 openmp 的 atomic 操作,可以避免多个线程操作同一数据。m.lock()
给 mutex 上锁,如果已经被别人上锁就暂停该线程并等待解锁。m.try_lock()
试图上锁,如果已经被别人上锁就返回 false
。m.unlock()
解锁。
m.lock()
和 m.unlock()
之间发生 throw,通常不直接调用他们,而是用 std::lock_guard<std::mutex> guard(m)
(相当于 lock),当 guard
被 destroy 时,会自动 unlock。
std::this_thread::sleep_for(std::chrono::seconds(2));
可以让某个线程暂停。
例程(编译时要给 linker 加上 -l pthread
):
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
mutex mut;
// A dummy function
void myfun(int id, int *i)
{
if (id == 1)
this_thread::sleep_for(chrono::milliseconds(100));
lock_guard<mutex> guard(mut);
printf("id = %d, i = %d\n", id, *i);
int j = *i+1;
if (id == 2)
this_thread::sleep_for(chrono::milliseconds(100));
*i = j;
}
int main()
{
int i = 0;
thread th1(myfun, 1, &i);
thread th2(myfun, 2, &i);
myfun(0, &i);
th1.join();
th2.join();
return 0;
}
另外也可以把 mut
声明为 myfun()
中的一个 static
变量。
另外注意 mutex
不光适用于 std::thread
,对任何其他 threading 库例如 pthread
或者 OpenMP 都有效。
thread_local
,可以让其在每个线程中保持自己独立的 copy,使函数变得 thread safe。例如上面的 myfun
中如果声明了 thread_local static vector<int> a;
,那么每个线程第一次调用该函数时就会生成一个独立的变量 a
,若一个线程多次调用该函数,那么每次调用时 a
都会有上次调用结束前的值。
 
 
 
 
 
 
 
 
 
 
 
友情链接: 超理论坛 | ©小时科技 保留一切权利