贡献者: 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),当该变量被 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;
}
 
 
 
 
 
 
 
 
 
 
 
友情链接: 超理论坛 | ©小时科技 保留一切权利