C++ 之 并发编程基础

时间:2021-04-29 12:07:22   收藏:0   阅读:0

C++并发编程基础

在C++线程库中提供一个native_handle()成员函数,允许通过使用平台相关API直接操作底层实现。

为了并发地运行函数,需要使用特定的函数以及对象来管理各个线程。C++在头文件中提供了管理线程的类和函数

一个简单的Hello, Concurrent World程序:

#include <iostream>
#include <thread>  //①
void hello()  //②
{
  std::cout << "Hello Concurrent World\n";
}
int main()
{
  std::thread t(hello);  //③
  t.join();  //④
}

其中 调用方法std::thread ,可见仍属于std域;同时使用join函数是为了保证t线程执行完毕后main主线程才结束。

启动线程

线程在线程对象创建时启动,即构造线程std::thread对象时便会启动。也就是说我们需要进行共享变量的设置才可以实现线程之间的相互控制。

std::thread my_thread(background_task);		// 1
std::thread my_thread((background_task())); // 2
std::thread my_thread{background_task()};   // 3
t.detach(); //(分离式),new和current线程无关
t.join();	//(加入式),阻塞current线程,执行新线程
std::thread t(update_data_for_widget,w,std::ref(data));

数据同步的安全性实现

std::mutex mt;
void addmethod(int a)
{
    mt.lock();
    addprocessing(...);
    mt.unlock();
}
void deletemethod(int a)
{
    mt.lock();
    deleteprocessing(...);
    mt.unlock();
}

使用unique_lock或者lock_guard实现上锁。

std::mutex mt;
void addmethod(int a)
{
    std::unique_lock<std::mutex> lock(mt);
    addprocessing(...);
}
void deletemethod(int a)
{
    std::unique_lock<std::mutex> l(mt);
    deleteprocessing(...);
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!