C++ 多线程笔记(std::thread)

                     

贡献者: addis

   例程(编译时要给 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;
}

  

未完成:互斥锁、条件锁、读写锁以及自旋锁分别什么时候用?

                     

© 小时科技 保留一切权利